Character键盘输入转向与旋转
操作键盘反馈Player主角的位移和转向
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lemon : MonoBehaviour
{
public float rotateSpeed = 20f;
//1. 获取玩家输入, 移动角色
//2. 走动的转向问题
//3. 动画问题
private Vector3 _movement;
private float _horizontal;
private float _vertical;
private Rigidbody _rigidbody;
private Animator _animator;
private Quaternion _rotation = Quaternion.identity;//转向初始化为不旋转
void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
_horizontal = Input.GetAxis("Horizontal");
_vertical = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
refreshMoveMent();
refreshRotation();
refreshAnimation();
}
private void refreshMoveMent()
{
//组装
_movement.Set(_horizontal, 0.0f, _vertical);
_movement.Normalize();
}
private void refreshRotation()
{
Vector3 desiredForward = Vector3.RotateTowards(transform.forward, _movement, rotateSpeed * Time.deltaTime, 0f);
_rotation = Quaternion.LookRotation(desiredForward);
}
private void refreshAnimation()
{
bool isMoveHorizontal = !Mathf.Approximately(_horizontal, 0.0f);
bool isMoveVertical = !Mathf.Approximately(_vertical, 0.0f);
bool isWalking = isMoveHorizontal || isMoveVertical;
_animator.SetBool("IsWalking", isWalking);
}
private void OnAnimatorMove()
{
//动画移动的距离*方向
_rigidbody.MovePosition(_rigidbody.position + _movement * _animator.deltaPosition.magnitude);
_rigidbody.MoveRotation(_rotation);
}
}