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

时间:2014-01-30 02:54:24

标签: unity3d

我的角色(暂时)是一个立方体。多维数据集使用C#脚本和Rigid Body组件进行映射。

我在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;
  }
}

行为变为:http://youtu.be/NYPNgAulc-k

我希望角色左/右转90度并开始在新方向上加速。但现在,在它转变之后,它会在曲线上加速。有关详细信息,请参阅上述视频。

我错过了什么?


更新(1月30日):transform.right更改为transform.forward并移除速度更改行:

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);
  }
}

导致向另一个方向移动(因此我改变了相机指向矢量)&左箭头或右箭头不改变方向;只有Runner对象旋转。

演示视频:http://youtu.be/UVG6l14oyjw


更新(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是一个布尔值,当Runner对象触地时设置为true。但是,在它离开地面之前,它沿着Z轴移动。当装置离开地面时,它会滑动到X-Z轴。更新问题的这一部分将单独询问:here

注意:鉴于Runner对象的质量为3。

1 个答案:

答案 0 :(得分:2)

来自documentationTransform.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);
}