public class PlayerControl : MonoBehaviour
{
private Animator ani;
private Rigidbody rgb;
public Camera cam;
public float speed;
private Quaternion targetRotation;
public float ratio;//旋转时的比率
private void Start()
{
ani = GetComponent<Animator>();
rgb = GetComponent<Rigidbody>();
cam=Camera.main;
}
private void Update()
{
RotatePlayer();
MovePlayer();
ani.SetBool("IsRoll", Input.GetKeyDown(KeyCode.LeftShift));
}
/// <summary>
/// 控制移动和移动方向
/// </summary>
private void MovePlayer()
{
float h_Abs=Mathf.Abs(Input.GetAxis("Horizontal"));
float v_Abs=Mathf.Abs(Input.GetAxis("Vertical"));
float max_hv=Mathf.Max(h_Abs,v_Abs);
ani.SetFloat("WalkOrRun", max_hv);
if (max_hv > 0.5)
{
rgb.velocity = transform.forward * speed;//移动方向为自身前方
}
else
{
rgb.velocity=Vector3.zero;
}
}
/// <summary>
/// 旋转是以摄像头方向为基准
/// 使用WASD键控制旋转
/// </summary>
private void RotatePlayer()
{
if (Input.GetKey(KeyCode.W))//只要方向键按下就会不断执行下面的方法
{
QuaControl(0);
}
if (Input.GetKey(KeyCode.S))
{
QuaControl(180);
}
if (Input.GetKey(KeyCode.A))
{
QuaControl(270);
}
if (Input.GetKey(KeyCode.D))
{
QuaControl(90);
}
}
//按一定比率从当前角度转到目标角度
private void QuaControl(int angle)
{
targetRotation = Quaternion.Euler(0, cam.transform.eulerAngles.y+angle, 0);//目标角度
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, ratio);//从当前角度转到目标角度
}
}
WASD键控制3D人物移动与转向,(已使用Cinemachine,鼠标可控制视角)人物转向以摄像头相关方向为基准
最新推荐文章于 2024-08-21 22:25:03 发布