Move to position - Arcade Physics

I am trying to have a sprite jump platform to platform in a left to right motion (see the image below)

I am not sure about the best way to go about this but I have implemented arcade physics. Ideally I want the sprite to jump to the next platform to an exact position or an exact distance so just pushing with an amount of velocity doesn’t seem correct. I have included a stack blitz coded example of doing so - all the source code is there too - any help would be greatly appreciated. Thanks

Adding code here for historical purposes:

var config = {
  type: Phaser.AUTO,
  scale: {
width: 300,
height: 480
  },
  scene: {
preload: preload,
create: create,
update: update
  },
  physics: {
default: 'arcade',
arcade: {
  debug: false
},
  },
  backgroundColor: "#6E615E"
};
const game = new Phaser.Game(config);
let box;
function preload() {}
function create() {
box = this.add.rectangle(80, 420, 20, 20, 0xffffff); 
const groundLeft = this.add.rectangle(0, 480-20, 100, 20, 0x6666ff).setOrigin(0,0);
const groundRight = this.add.rectangle(200, 480-20*4, 100, 20, 0x6666ff).setOrigin(0,0);

this.physics.add.existing(box);
this.physics.add.existing(groundLeft);
this.physics.add.existing(groundRight);
box.body.gravity.y = (100);
groundLeft.body.immovable = true;
groundRight.body.immovable = true;
this.physics.add.collider(groundLeft, box);
this.physics.add.collider(groundRight, box);

this.input.on('pointerdown', ()=>{
  box.body.setVelocityY(-110);
  box.body.setVelocityX(100);
});
} 
function update() {
  if(box.x > 300 || box.y > 480) {
this.scene.restart();
  }
}

I think you can still do it with velocity as long as you stop the box at the end of the jump. You could do that in a collision callback or in update(). Here it is in update():

https://stackblitz.com/edit/phaser-3-jump-test-g3jd2k?embed=1&file=index.js

Thanks a lot for the reply. Not sure if that link saved when you made the changes. It seems to take me to the same as what I posted.

1 Like

I was afraid of that :smiley:

Depending on exactly what you want, you could do

function update() {
  if (box.body.touching.down) {
    box.body.stop();
  }
  // …
}

or

function create() {
  // …
  this.physics.add.collider(groundLeft, box, collideGroundVsBox);
  this.physics.add.collider(groundRight, box, collideGroundVsBox);
  // …
}

function collideGroundVsBox(ground, boxOnGround) {
  boxOnGround.body.stop();
}
1 Like

Nice this is looking good - thanks @samme!

Solution outcome: