4

I made a sphere in Babylon.js at the point [0,0,0], I want it to be like a planet with it's own gravity.

Then I want a sphere (that will be the player) to be attracted to the center of the big sphere ("planet").

Here is the demo I made. http://www.babylonjs-playground.com/#DETZ7#1

The only solution I can still think is to update the gravity values dinamically, but I don't know if it's a best pratice in this situation. If you know some better way to do it, please let me know, I started learning it today.

Thank you in advance.

Giovanne Afonso
  • 666
  • 7
  • 21

1 Answers1

4

You can make your "planet gravity" force in Cannon.js by applying a force on the player body on every physics tick. The force should be directed at the center of the planet. You also need to cancel the gravity force that the physics world applies every step.

This is mainly what I added to your code to implement the gravity force. Note that I also changed your makePlayer function so it returns the CANNON.Body instead of your player mesh. I also made sure to set the gravity of the world to exactly -10 in the Y direction, for simplicity.

// Listen for physics ticks
playerBody.world.addEventListener('postStep', function () {

    // Direction towards (0,0,0)
    playerBody.force.set(
        -playerBody.position.x,
        -playerBody.position.y,
        -playerBody.position.z
    ).normalize();

    // Set magnitude to 10
    playerBody.force.scale(10, playerBody.force);

    // Cancel gravity force from the world
    playerBody.force.y += 10;

});

Here's the updated playground scene: http://www.babylonjs-playground.com/#DETZ7#4

schteppe
  • 1,984
  • 13
  • 15