我正在尝试在Unity中制作一款游戏,这个游戏使用了一辆汽车。我想让汽车移动,到目前为止我已经可以让它向前、向后运动,并且我也可以将其向左、向右旋转,这两种移动都很顺利。
但是,当我将其向右旋转后,尝试让其向前移动时,它会以与之前相同的方向移动,而不考虑刚才进行的转弯。它的移动方式就像一侧前进时旋转了。我一直试图调整向前矢量的值,但是我的尝试都没有产生好的结果。如果有人有好的想法,我很愿意听听。
但是,当我将其向右旋转后,尝试让其向前移动时,它会以与之前相同的方向移动,而不考虑刚才进行的转弯。它的移动方式就像一侧前进时旋转了。我一直试图调整向前矢量的值,但是我的尝试都没有产生好的结果。如果有人有好的想法,我很愿意听听。
public class CarMovement : MonoBehaviour
{
public Rigidbody rb;
public Transform car;
public float speed = 17;
Vector3 forward = new Vector3(0, 0, 1);
Vector3 backward = new Vector3(0, 0, -1);
Vector3 rotationRight = new Vector3(0, 30, 0);
Vector3 rotationLeft = new Vector3(0, -30, 0);
void FixedUpdate()
{
if (Input.GetKey("w"))
{
rb.MovePosition(car.position + forward * speed * Time.deltaTime);
}
if (Input.GetKey("s"))
{
rb.MovePosition(car.position + backward * speed * Time.deltaTime);
}
if (Input.GetKey("d"))
{
Quaternion deltaRotationRight = Quaternion.Euler(rotationRight * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotationRight);
}
if (Input.GetKey("a"))
{
Quaternion deltaRotationLeft = Quaternion.Euler(rotationLeft * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotationLeft);
}
}
}
< p > < em >稍后编辑:我提出这个问题的原因是我不知道向量 car.forward 与我写的静态向量不同。在评论中的解释后,我理解了自己犯的错误。
car.forward
。 - Eliasar