Set local position using Rigidbody

Hi there,
How to achieve the same result as the script below using rigidbody?

transform.localPosition = any Vector3 value;

According to the documentation, rigidbody.position should be used for teleporting the object to a specific position.

However, rigidbody.position expects world-space coordinates and according to your code snippet, you want to use local coordinates instead.

In this case transform.TransformPoint can be used to convert local-space coordinates to world-space coordinates.

Untested:

rigidbody.position = transform.TransformPoint(localPosition);
2 Likes

Thank you. I actually tried this before, but for some reason the position doesn’t update at all. Here I am trying to update the rigidbody position from another object script.

Debug.Log(waypointRB.name, waypointTransform.gameObject);
// waypointTransform.localPosition = Vector3.zero; // Working as expected
waypointRB.position = waypointTransform.TransformPoint(Vector2.zero); // Not working

I have also tried different rigidbody settings but the result is always the same.

In other case the same result occurs and the rigidbody does not move at all:

float time = 0;
float duration = 0.5f;
Vector3 from = transform.position;
Vector3 to = waypointTransform.position;

 while (time < duration)
 {
     //transform.position = Vector3.Lerp(from, to, time / duration); Working as expected
     rb.MovePosition(Vector3.Lerp(from, to, time / duration)); // rigidbody not moving at all
     time += Time.deltaTime;
     yield return null;
}

What could be the reason?

If there are any other components of the object, such as an Animator or CharacterController, which drive the movement of the object, they are probably writing their changes to the transform and clobbering the Rigidbody’s attempt to do the same.

1 Like

No such components. Changing position using transform.localposition works as expected. Just replacing the code with rigidbody, which results in this behavior.

Transform.TransformPoint(Vector2.zero) is entirely useless though. It’s literally just the same as using transform.position for a given transform.

I don’t think you actually need local position here. Using global positions will net you the same effect.

In any case you likely have something controlling the position of the rigidbody still.

1 Like

In addition to that, using a Vector2 instead of a Vector3 may also produce incorrect results. Not for Zero, but potentially any other coordinate.

2 Likes