对于 Unity 和 C# 来说还是很陌生。当涉及到设置/更改对象的位置时,我通常可以找到解决方法,但是当涉及到旋转时,对于四元数、欧拉角等,它仍然令我难以置信。
我试图检查一个物体(头部)是否面向某个方向,如果它没有面向该方向,则需要根据它的走向(上、下、左或右)将其设置为该方向。这是我目前正在开发的贪吃蛇游戏(就像旧的自上而下的诺基亚游戏)。
我试图查找它,但没有一个答案特定于我想要做的事情。
到目前为止,这就是我为玩家输入的内容(代码片段):
private int GetAxisRaw(Axis axis)
{
if (axis == Axis.Horizontal)
{
bool left = Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A);
bool right = Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D);
if (left)
{
snakeHeadRotation.transform.Rotate(0, 180, 0); // Keeps rotating when left is pressed
return -1;
}
if (right)
{
snakeHeadRotation.transform.Rotate(0, -180, 0);
return 1;
}
return 0;
}
如你所见,snakeHeadRotation.transform.Rotate(0, 180, 0);例如,每次玩家按下左键时都会被调用,从而转动蛇的头部,即使蛇仍在向左移动。
我的逻辑是将旋转值存储在某处(可能输入 Quaternion/bool),并检查该旋转值是否与设置为左侧的当前旋转值匹配(即 SnakeHeadRotation.transform.Rotate(0, 180 , 0);) 如果是这种情况,请不要执行任何操作。如果不是,请将其设置为snakeHeadRotation.transform.Rotate(0, 180, 0);例如。
代码看起来像(写出来):
private int GetAxisRaw(Axis axis)
{
if (axis == Axis.Horizontal)
{
bool left = Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A);
bool right = Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D);
if (left && rotation is not equal to snakeHeadRotation.transform.Rotate(0, 180, 0))
{
snakeHeadRotation.transform.Rotate(0, 180, 0);
return -1;
}
if (right)
{
snakeHeadRotation.transform.Rotate(0, -180, 0);
return 1;
}
return 0;
}
如上所述,我对设置或存储旋转值非常不熟悉。我怎样才能实现这个目标?这是正确的方法还是有更合乎逻辑的方法?我自己无法弄清楚这个问题..
我希望我解释得对,我通常不善于解释事情。
最佳答案
使用 Transform.Rotate(x)
将使您的头部相对于当前头部方向旋转 x
度。
我想你想要的是根据你按下的箭头键设置你头部的绝对旋转。因此,即使您多次按下同一个箭头键,头部也会保持在正确的方向。
为此,您可以为每个头部方向创建 4 个旋转,因此可以根据需要使用它们。
例如,如果您的头默认面向向前
:
// create your directions
private static Quaternion forwardDirection = Quaternion.Identity;
private static Quaternion rightDirection = Quaternion.FromToRotation(Vector3.forward, Vector3.right);
private static Quaternion leftDirection = Quaternion.FromToRotation(Vector3.forward, Vector3.left);
private static Quaternion backDirection = Quaternion.FromToRotation(Vector3.forward, Vector3.back);
...
private int GetAxisRaw(Axis axis)
{
...
if (left)
{
// set the absolute direction of your head to the left
snakeHeadRotation.transform.rotation = leftDirection;
return -1;
}
if (right)
{
// set the absolute direction of your head to the right
snakeHeadRotation.transform.rotation = rightDirection;
return 1;
}
...
}
关于c# - 如何在 Unity C# 中检查对象是否面向某个方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66472309/