Unity3d 使用RigidBody.AddRelativeForce更改方向时的奇怪行为

Unity3d 使用RigidBody.AddRelativeForce更改方向时的奇怪行为,unity3d,Unity3d,我的角色(暂时)是一个立方体。立方体使用C#脚本和刚体组件进行映射 我在Update()中使用以下代码更改角色(刚体)的方向: void Update () { rigidbody.AddRelativeForce(transform.right * speed, ForceMode.Acceleration); if (Input.GetKeyDown(KeyCode.LeftArrow)) { gameObject.transform.Rotate(0, -90, 0);

我的角色(暂时)是一个立方体。立方体使用C#脚本和刚体组件进行映射

我在
Update()
中使用以下代码更改角色(刚体)的方向:

void Update () {
  rigidbody.AddRelativeForce(transform.right * speed, ForceMode.Acceleration);
  if (Input.GetKeyDown(KeyCode.LeftArrow)) {
    gameObject.transform.Rotate(0, -90, 0);
    rigidbody.velocity = transform.right* rigidbody.velocity.magnitude;
  }
  if (Input.GetKeyDown(KeyCode.RightArrow)) {
    gameObject.transform.Rotate(0, 90, 0);
    rigidbody.velocity = transform.right* rigidbody.velocity.magnitude;
  }
}
行为变成:

我希望角色向左/向右旋转90度,并开始准确地向新方向加速。但现在,在转弯后,它在曲线上加速。有关更多信息,请参阅上面的视频

我错过了什么


更新(1月30日):更改了
变换。右
变换。向前
并删除变速线:

void Update () {
  rigidbody.AddRelativeForce(transform.forward * speed, ForceMode.Acceleration);
  if (Input.GetKeyDown(KeyCode.LeftArrow)) {
    gameObject.transform.Rotate(0, -90, 0);
  }
  if (Input.GetKeyDown(KeyCode.RightArrow)) {
    gameObject.transform.Rotate(0, 90, 0);
  }
}
这会导致向另一个方向移动(因此我改变了相机的指向向量)&当向左或向右箭头时,不会改变方向;只有流道对象旋转

演示视频:


更新(2月4日):应用了@Roboto下面的答案,并做了一些修改:

void Update () {
     if (Input.GetKeyDown(KeyCode.LeftArrow)) {
       transform.Rotate(0, -90, 0);
       rigidbody.velocity = Vector3.zero;
       rigidbody.angularVelocity = Vector3.zero;
     }
     if (Input.GetKeyDown(KeyCode.RightArrow)) {
       transform.Rotate(0, 90, 0);
       rigidbody.velocity = Vector3.zero;
       rigidbody.angularVelocity = Vector3.zero;
     }
}

void FixedUpdate() {
    // Physics stuff should be done inside FixedUpdate :)
    rigidbody.AddForce(transform.forward * speed, ForceMode.Acceleration);
}
转弯终于可以了。我有一个使角色跳跃的额外函数。在
Update()
中,我添加了:

if ((Input.GetButtonDown("Jump") || isTouched) && isOnGround) {
    isOnGround = false; 
    rigidbody.AddForce(jumpHeight, ForceMode.VelocityChange);
}
其中,
isOnGround
是一个布尔值,当跑步者对象接触地面时设置为true。但是,在离开地面之前,它会沿Z轴移动。当装置离开地面时,它会向X-Z轴滑动。更新问题的这一部分单独提问:

注意:假设转轮对象的质量为3。

来自,
Transform.forward

The blue axis of the transform in world space.
世界空间,因此我们希望使用
AddForce
而不是
AddRelativeForce
,因为
AddRelativeForce
将使用局部坐标系来添加力

所以这是可行的:

void Update () {
     if (Input.GetKeyDown(KeyCode.LeftArrow)) {
       transform.Rotate(0, -90, 0);
     }
     if (Input.GetKeyDown(KeyCode.RightArrow)) {
       transform.Rotate(0, 90, 0);
     }
}

void FixedUpdate() {
    // Physics stuff should be done inside FixedUpdate :)
    rigidbody.AddForce(transform.forward * speed, ForceMode.Acceleration);
}

对不起,我对Unity很陌生。我应该如何修改代码以实现我的预期行为?更改为
transform.forward
后,框从开始处向左移动,而不是向前移动。是的,您更新的答案会引导我找到正确的方法。请参阅我的问题更新。谢谢,当然可以。也许我会在一个新问题中进一步提问。