在Unity中通过输入行为控制角色转向
注:控制采用InputSystem,此处省略,传统输入同样适用
方案
存在以下3个可行方案
- 自行根据输入计算需要偏转的角度,且使用平滑过渡
- 使用Quaternion.LookRotation()方法,且使用平滑过渡
- 使用Transfrom.LookAt()方法,此方法不存在过渡
{
//自己计算转向
float horizontalAngle = Mathf.Atan2(player.inputSystem.playerMovement.x, player.inputSystem.playerMovement.z) * Mathf.Rad2Deg;
// float verticalAngle = Mathf.Atan2(player.inputSystem.playerMovement.y, new Vector2(player.inputSystem.playerMovement.x,player.inputSystem.playerMovement.z).magnitude) * Mathf.Rad2Deg;
// Vector3 targetEulerAngles = new Vector3(verticalAngle, horizontalAngle, 0f);
Vector3 targetEulerAngles = new Vector3(0f, horizontalAngle, 0f);
player.transform.rotation = Quaternion.Slerp(player.transform.rotation, Quaternion.Euler(targetEulerAngles), Time.deltaTime * 10f);
}
//从inputSystem中获取值,需求中不存在Y轴的输入,故而Vector3中Y的值设置为0
//Vector3 movement = new Vector3(player.inputSystem.playerMovement.x, 0f, player.inputSystem.playerMovement.z);
{
//使用Quaternion.LookRotation转向
// player.transform.rotation = Quaternion.Slerp(player.transform.rotation, Quaternion.LookRotation(movement), Time.deltaTime * 10f);
}
{
//LookAt直接转向,不存在过渡
// player.transform.LookAt(player.transform.position + movement.normalized);
}
效果
U3D平滑移动