How to decelerate before arrival while using moveTo/moveToObject?

I’m trying to find best solution for a point and click spaceship (sprite) movement on a 2d top-down view using mouse click.

I want my spaceship to slowly loose speed just before it’s arrival at the destination and I don’t want it to overshoot it’s target. I want it to arrive to exact position I clicked on (x, y).

I didn’t find any easy solution to achive this, it seems to me like I need to manually calculate the moment (distance to target) at which I need to start decelerate, does anyone have any good tips, where to start? I’m intending to use Phaser Arcade Physics (but not necessarily sticking with it). I know there’s drag property that can slow down my spaceship - but I still need to know at which point I should apply it (and with what values for x and y).

Funnily enough Phaser 2 seems to have this implemented:

Maybe there’s some easy solution for this that I’m not aware of.

One way is

const dist = Phaser.Math.Distance.BetweenPoints(source, target);
const speed = 200;
const time = dist / speed;

// Call this *once* per click
this.physics.moveToObject(source, target, speed);

source.body.setDrag(
  Math.abs((0.5 * source.body.velocity.x) / time),
  Math.abs((0.5 * source.body.velocity.y) / time)
);
1 Like

And another way is to modify the velocity continuously:

function update() {
  // Decelerate from `maxSpeed` starting at `maxDist` from target
  var maxSpeed = 200;
  var maxDist = 100;
  var dist = Phaser.Math.Distance.BetweenPoints(source, target);

  var t = Phaser.Math.Linear(0, 1, dist / maxDist);
  t = Phaser.Math.Clamp(t, 0, 1);
  t = Phaser.Math.Easing.Quadratic.Out(t);

  this.physics.moveToObject(source, target, t * maxSpeed);
}
1 Like

Thank You very much kind sir :slight_smile: