学习目标:
实现人物及时根据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转向。