# Planet gravity? [duplicate]

I am trying to make a game with the Phaser game engine and would like to implement some sort of planetary gravity. Essentially I just want the player to be able to walk on a circle or orbit a point. I was wondering what would be the best way to do this in phaser. I know that you can set objects gravities but you can only do so in the x and y direction.

• What's "360-degree gravity"? Do you mean Newton's law of universal gravitation? – Anko Mar 2 '14 at 13:37
• No I want the player to be able to walk along a circular planet but phaser only allows you to apply gravity in one particular y direction and one particular x direction. – user3344581 Mar 2 '14 at 18:32
• Not sure but you could probably deduce the gravity direction from the normals of your mesh. – Sidar Mar 2 '14 at 19:37
• Try communicating what you mean more clearly. You probably have a nice picture in your mind's eye of exactly what you're talking about but you have not done a good job of conveying it to us. – Steve H Mar 3 '14 at 2:26

Phaser doesn't have built-in support for any fancier gravity, so you'll have to roll your own. Fortunately it's fairly easy to understand, so you just calculate your own gravity in the game's update() function, which is simply a (properly scaled) vector from your player to the planet's center of gravity, and set your player's body.gravity property, or you can manually add the gravity vector to the body.velocity property.

Here's an example of the first approach: http://jsfiddle.net/gJ4kA/

function create() {

// Use our own gravity
ship.body.allowGravity = false;
// Set an initial motion
ship.body.velocity.x = 100;

}

function update() {

// Calculate gravity as the normalised vector from the ship to the planet
ship.body.gravity = new Phaser.Point(planet.body.x - ship.body.x, planet.body.y - ship.body.y);
// Normalize and multiply by actual strength of gravity desired
ship.body.gravity = ship.body.gravity.normalize().multiply(300, 300);

}


This is probably not accurate enough if you're making a simulation, but for simple games it is fine.

• This is pretty much the answer I was looking for I appreciate the help! – user3344581 Mar 3 '14 at 19:37
• Is there any way to only have the gravity be multiplied once, right now it is being multiplied every time update is called resulting in increasing gravity. Thanks! – user3344581 Mar 4 '14 at 21:48