[Unity2D]实现人物及时根据Animator同步按键动作

学习目标:

实现人物及时根据Animator同步按键动作

了解一下animator

视频参考:秦无邪OvO的个人空间_哔哩哔哩_Bilibili

以及自己画的像素帧图


学习前提:

上篇文章说到人物会左右移动,然而动画系统还未建立联系,现在说下怎么实现人物及时根据Animator同步按键动作


学习内容:

我们在Animator中点开发现有几个Animation,按住Alt可以拖动他们到理想的位置,

接着在左侧栏创建一个bool类型的条件,名字就叫Walk,在Idle和Walk之间分别创立Make Transition,不需要Has Exist Time,在Conditions处创立Walk条件 

(这里说错名字了,ma把Run改成Walk)、

让我们回到PlayerController的C#脚本来。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float walkSpeed;
  

    private Animator myAnim;
    private BoxCollider2D boxcollid2D;
    private Rigidbody2D rb2D;

    private bool isFlip = false;
    void Start()
    {
        myAnim = GetComponent<Animator>();
        boxcollid2D = GetComponent<BoxCollider2D>();
        rb2D = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Flip();
        Walk();
        
    }
    void Flip()
    {
        // Mathf.Epsilon是一个很小的浮点值
        bool isPlayerHasXAxis = Mathf.Abs(rb2D.velocity.x) > Mathf.Epsilon;
        //如果x轴上有速度
        if (isPlayerHasXAxis)
        {
            //如果速度的方向是向右
            if(rb2D.velocity.x > 0.1f)
            {
                transform.localRotation = Quaternion.Euler(0, 0, 0);
            }
            //如果速度的方向是向左
            if (rb2D.velocity.x < -0.1f)
            {
                transform.localRotation = Quaternion.Euler(0,180, 0);
            }
        }
    }
    void Walk()
    {
        float moveDir = Input.GetAxis("Horizontal");
        Vector2 playerVel = new Vector2(moveDir * walkSpeed, rb2D.velocity.y);
        rb2D.velocity = playerVel;
        bool isPlayerHasXAxis = Mathf.Abs(rb2D.velocity.x) > Mathf.Epsilon;
        //true则向右,false则向左
        myAnim.SetBool("Walk", isPlayerHasXAxis);
    }
}
 

学习产出:

转方向成功! 

 本次学习了代码中用一个极小的浮点值判断Player x轴方向上有没有速度,调用动画中名为Walk的bool值,转向要单独写一个封装的方法,所有的方法都要放在void Update()中每帧执行,通过判断x的速度的正负值,用transform.localRotation转向。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值