Setting Rigidbody2D.position doesn't always update Transform.position

Hello,

I am starting a 2D project and am planning on using Cinemachine to track my character. During testing there was some regular jerking happening while the tracked object was moving. I was finally able to track this down to calls to Rigidbody2D.position not always being applied to the transform.

The code below will show the problem:

using UnityEngine;

public class Dummy : MonoBehaviour
{
    public float speed = 5f;

    private Rigidbody2D rb2d;

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        float v = speed * Time.fixedDeltaTime;

        // Set the transform's position based on the Horizontal axis
        rb2d.position = rb2d.position + new Vector2(
            Input.GetAxis("Horizontal") * v,
            0);

        // Draw a line from the new Rigidbody2D's position to the
        // transform's position. Should draw lines leaning away from
        // the object.
        Debug.DrawLine(
            rb2d.position,
            transform.position + Vector3.up * 0.5f,
            Color.white,
            2);
    }
}

This code moves the object using Rigidbody2D.position according the the current value of the “Horizontal” axis. If the object is moving at a constant rate it is expected that the lines that are drawn would be parallel and leaning away from the object.

What I am seeing in reality is that at a regular interval (every 25th fixed update) the position of the Transform does not change as shown in the image below.

Is this a bug? Is there some setting that controls this? In my testing this only happens by setting the Rigidbody2D.position. Setting the Rigidbody2D.velocity does not cause this problem.

Thank you

Try using the method rigidBody.MovePosition(position) instead. If that fails then the problem is likely not with unity but with how your gameobject is structured. For example, if the rigidbody is actually inside a child object, expecting it to update the parent’s transform would be incorrect.

Thank you for the reply. Calling that method does fix the problem. I still believe that it is not working as intended. The object is a root object, with no parent and no children.

What is it that makes you think it isn’t quite working right?

Setting the Rigidbody2D position doesn’t immediatley change the Transform position. The Transform is only updated during the fixed-update after the simulation has run which can run several times per-frame occasionally to keep up with game time. It’s the same with MovePosition which only runs during fixed-update.

You can run the simulation per-frame if you wish by turning off Physics2D.AutoSimulation and performing the simulation manually using Physics2D.Simulate.

I can only assume that this is a kinematic body you’re moving directly. You should try to avoid this though because you won’t get interpolation and you’ll cause tunnelling.