top of page

Unity | How to move objects correctly

At first glance, it would seem that

transform.position += direction*SPEED*Time.deltaTime;

is the answer to this question, and everything beyond that is an extra fluff, special case that nobody needs. But not exactly. There are 2 parts to the movement:

  • visual smoothness

  • accurate physical interactions.

If both parts are important, then the right way may be a bit more tricky. To get accurate physics, the recipe is fairly straightforward: Move the object from FixeUpdate() and not from Update();

FixedUpdate() => 
rigidbody.MovePosition(rigidbody.position + direction*SPEED*Time.fixedDeltaTime);

Tiny jitter.

Fixed updates may execute once, twice or zero times between frames. So one frame you get an update, in the other one - you don't - the character is frozen for that frame. After that, you may get 2 in a row. So even in fairly good FPS scenarios, the character moves twice as much during some frames than during other frames. And that is something you may notice, especially when the camera is moving with the character.

There is a way to combine the best of both worlds:

Update position in both LateUpdate() and FixedUpdate(). From both of them call the UpdateMovement() method:

UpdateMovement()
{
	float deltaTime = Time.time - previousMoveTime;
	previousMoveTime = Time.time;
	transform.position += direction*SPEED*deltaTime;
}

The only problem is that now we move the player's Rigidbody from Update(); which will cause the jittery behaviour of the physics system.

To account for that, I've made the player's collider into a separate object, and updated that object only from FixedUpdate();

FixedUpdate()
{
	UpdateMovement();
	rigidbodyProxy.MovePosition(transform.position); 
}

And now the player moves smoothy and interacts correctly)

Comments


bottom of page