是这样的,我想实现根据按键(wasd),使方块根据对应的轴缓慢旋转90度(xy)。
但是在实现过程中,发现旋转总是会发生奇怪的错误,貌似这个问题是因为万向锁造成的,但是我不清楚该如何解决.
以下是问题代码,不知道该如何修改:
void Update()
{
//获取按键方向
if (Input.GetKeyDown(KeyCode.D))
direction = Direction.Right;
else if (Input.GetKeyDown(KeyCode.A))
direction = Direction.Left;
else if (Input.GetKeyDown(KeyCode.W))
direction = Direction.Up;
else if (Input.GetKeyDown(KeyCode.S))
direction = Direction.Down;
//更新目标旋转角度
if (Input.anyKeyDown)
{
if (direction == Direction.Up)
rotate = Quaternion.Euler(rotate.eulerAngles.x + -90, rotate.eulerAngles.y, rotate.eulerAngles.z);
else if (direction == Direction.Down)
rotate = Quaternion.Euler(rotate.eulerAngles.x + 90, rotate.eulerAngles.y, rotate.eulerAngles.z);
else if (direction == Direction.Left)
rotate = Quaternion.Euler(rotate.eulerAngles.x, rotate.eulerAngles.y + -90, rotate.eulerAngles.z);
else if (direction == Direction.Right)
rotate = Quaternion.Euler(rotate.eulerAngles.x, rotate.eulerAngles.y + 90, rotate.eulerAngles.z);
}
//实时刷新旋转角度
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotate, 2f);
}