Center gravity

Hi!

For my first project and learning Phaser I’m creating a version of Spacewar (a game from as far back as 1962, I believe). This game has two ships shooting at each other, and a planet with gravity in the middle of the screen.

In my version I want realistic’ish gravity.

Wwhat I’ve done is calculated the square of the distance between the gravity point and the ship, and applied a force in the opposite direction, proportional to the inverse of the square of the distance.

To avoid extreme forces, I apply 0 when the ship is “inside” the planet. (This is also when the ship will go BOOM later.)

  state.players.forEach( (player, i) => {

    const playerPosition = new Phaser.Math.Vector2(player.ship.x, player.ship.y);
    const gravityVector = (new Phaser.Math.Vector2(state.world.gravity.pos)).subtract(playerPosition);
    const gravityLengthSquare = gravityVector.lengthSq();

    if (gravityLengthSquare < sunSizeSq) {
      // BOOM!
    }
    else {
      gravityVector.setLength( delta * state.world.gravity.force / gravityLengthSquare );
      player.ship.body.acceleration=gravityVector;
    }

  });

What happens is that this gives the ship more and more speed. I suspect the reason is that the increased speed makes the distance between two steps increase so quickly that the force in the opposite direction of movement becomes too small. There should probably be some kind of integration over the moved distance instead.

The question is for a simple algorithm for this, or if this functionality already exists in Phaser3?

There is accelerateTo.

Thanks for the tip.

I had a look at the function, and what it does is setting acceleration to a fixed constant, while what I ideally wanted is proportional to inverse square of distance.