EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

[Unity]Rigidbody.position相关问题汇总

Unity官方文档:

Description

The position of the rigidbody.

Rigidbody.position allows you to get and set the position of a Rigidbody using the physics engine. If you change the position of a Rigibody using Rigidbody.position, the transform will be updated after the next physics simulation step. This is faster than updating the position using Transform.position, as the latter will cause all attached Colliders to recalculate their positions relative to the Rigidbody.

Rigidbody.position允许你使用物理引擎获取和设置刚体的位置。

如果使用Rigidbody.position更改刚体的位置,则Transform将在下一个物理模拟步骤之后更新。

这比使用Transform.position更新位置更快,因为后者将导致所有附加的碰撞器重新计算它们相对于刚体的位置。

 

 

有点绕,你可能认为设置rigibody的坐标能直接影响GameObject的transform的坐标,因为看起来是这样的。

 

实际上,根据文档[3]的说法,

如果你想让GameObject移动,使用Transform.Translate函数即可完成,

通过改变物体在世界坐标的位置,然后乘以deltaTime,在void Update方法中更新,实现了物体移动。

  void Update() {
        transform.Translate(Vector3.forward * Time.deltaTime);
        transform.Translate(Vector3.up * Time.deltaTime, Space.World);
        transform.Translate(0, 0, Time.deltaTime);
        transform.Translate(0, Time.deltaTime, 0, Space.World);

    }

 

 

另一种方式是用Rigidbody.velocity来实现。

if (Input.GetButtonDown("Jump"))

rb.velocity = new Vector3(0, 10, 0);

像这样给一个向上的速度。

设置刚体速度可以让物体运动并且忽略静摩擦力。

 

 

 

关于下一个物理模拟步骤之后的解释说明:

按照文档[2]的说法,直接设置rigibody的坐标好像是不能获得期望的结果的,具体参考文档[5]

 

 

 

有一个方法专门解决这个问题:

This is similar to setting transform.position, however the position will only be applied to the transform at the end of the physics step. If you want to continously move a rigidbody or kinematic rigidbody use MovePosition and MoveRotation instead.

这个类似设置transform.position,然而position只在物理步骤结束之后应用到变换。 如果你想连续移动一个刚体或运动学刚体,请使用MovePosition和MoveRotation代替。

 

Rigidbody.position默认是和Transform的位置是同值的,不在重心位置。

 

参考文档:

[1] Unity官方文档 - Rigidbody.position

[2] Unity3d 中 Transform.position 与Rigidbody.position的同步问题

[3] Unity中transform与Rigidbody两种运动方式的比较

[4] Rigidbody.MovePosition 移动位置

[5] Unity3d 中 Transform.position 与Rigidbody.position的同步问题 - 加强版

This article was last edited at 2020-04-08 09:46:40

* *