So I’ve been doing some testing and I’ve come to the conclusion that MovePosition have a lag when moving a rigidbody. The included unitypackage comes with a simple scene with 2 instances of a prefab.
([56224-rigidbodytrouble.zip|56224])
That prefab is a rigidbody with:
- Interpolate: Set to “Interpolate”
- Use gravity: Unchecked
- Is Kinematic: Checked
In Update, the arrow keys are scanned to check if the game objects must be moved around.
One of the instances (Player 1) moves it’s position using transform.Translate in Update. The other (Player 2) uses rigidbody.MovePosition in FixedUpdate, where all physics interactions should be.
The code (very simple) is as follows:
[Range(1, 2)]
public int PlayerId = 1;
public float speed = 5;
private Rigidbody rigidBody;
private Vector2 input;
void Awake()
{
rigidBody = GetComponent<Rigidbody>();
}
void Update () {
input = new Vector2();
if (Input.GetKey(KeyCode.LeftArrow)) { input.x = -1; }
if (Input.GetKey(KeyCode.RightArrow)) { input.x = 1; }
if (Input.GetKey(KeyCode.UpArrow)) { input.y = 1; }
if (Input.GetKey(KeyCode.DownArrow)) { input.y = -1; }
if (PlayerId == 1)
{
Vector3 movement = Vector3.right * input.x * speed * Time.deltaTime;
movement += Vector3.forward * input.y * speed * Time.deltaTime;
transform.Translate(movement);
}
}
void FixedUpdate()
{
if (PlayerId == 2) {
Vector3 movement = Vector3.right * input.x * speed * Time.deltaTime;
movement += Vector3.forward * input.y * speed * Time.deltaTime;
rigidBody.MovePosition(rigidBody.position + movement);
}
}
In theory both game objects should move at the same time, maintaining their relative position between each other. But if you run this sample, you will notice that Player 2 have a noticeable lag between the moment the arrow is pressed and its actual movement on the screen.
While Player 1 (using translate) moves instantly as it should, Player 2 seems to do it at a different time. If you follow Player 2 in the Scene View (using Shift + F) and keep going in one direction, you will notice that eventually it will surpass Player 1.
Is there a solution to this problem? Is there something I’m missing or not understanding? This lag completely ruins precision gameplay, but I want to use the physics system.
Thanks in advance.