private CharacterController cc;//角色控制组件
private Animator animator;//角色的动画组件
public float speed = 5;//移动速度
private AnimatorStateInfo animStateInfo;//获取动画状态信息
void Awake()
{
cc = this.GetComponent<CharacterController>();
animator = this.GetComponent<Animator>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
animStateInfo = animator.GetCurrentAnimatorStateInfo(0);
if (Mathf.Abs(h)>0.1f|| Mathf.Abs(v) > 0.1f)//判断有键按下
{
animator.SetBool("Walk", true);
if (animStateInfo.IsName("Walk"))
{
Walk(h, v);
}
}
else
{
animator.SetBool("Walk", false);
}
if (Input.GetAxis("Attack")==1)
{
//如果按了攻击键则执行攻击方法
Attack();
}
}
private void Walk(float h,float v)
{
Vector3 targetDir = new Vector3(h, 0, v);
transform.LookAt(targetDir + transform.position);//向移动方向看
cc.SimpleMove(transform.forward * speed);//向前移动
}
private void Attack()
{
animator.SetTrigger("Attack1");
}
unity实现角色的移动(用状态机控制动画)
最新推荐文章于 2024-02-15 20:32:56 发布