Position is not updating until 2 update() calls

Hey there,

I am having an issue regarding updating the position of an element. I’ve made a Codepen here with an example.

In that example I have a physics object that I am moving to the left. If I detect that the x position of the object is less than or equal to 0 I set the velocity to 0 and the x position to 1. I would expect that this condition would fire once since inside the condition I am setting the x position to a value that would fail the condition.

If you run this example though you’ll see the console message gets printed twice. I’ve tried everything I can think of and tried to find more info regarding the update function in Phaser but I am stumped. It seems like even though I set velocity to 0 it still moves in that velocity for 1 more update.

Things I’ve tried:

  • Instead of this.enemy.x = 1 I used this.enemy.setPosition(1, this.enemy.y) but that didn’t change the behavior.
  • Setting the acceleration to 0.

Thanks, I appreciate any help!

:wave:

During scene update() the body has moved but the game object hasn’t yet. So I would do instead:

Oh interesting, I knew I wasn’t understanding something. Do you have more info regarding game objects vs body? Thanks!!!

  • Before the physics step(s), the body is positioned from the game object
  • During the physics step(s), the body is moved/collided
  • Scene update()
  • The game object is repositioned based on the body delta (not position!)

The upshot is that in collider callbacks and scene update() you should always read/write the body position.

Also during update() the physics body has already moved (for that step), so when you set velocity you’re affecting the next physics step.