I've added a body that should have gravity to my game, so picture a big empty screen with a circle for "Earth" in the middle.
What methods would let me have any other body added to the game be "accelerated" or "attracted" to this circle? Basically if an asteroid appears, it should keep it's initial velocity, but be affected by Earth's gravity.
I believe that I found this method that you're looking for here.
I also have an example of that method in action here.
Here is the source code for my example:
// Global constants
var GAME_WIDTH = 800;
var GAME_HEIGHT = 600;
var SHIP_X_POS = 100;
var SHIP_Y_POS = 200;
var PLANET_X_POS = 400;
var PLANET_Y_POS = 300;
var ACCELERATION_TOWARDS_PLANET = 500;
var SHIP_VELOCITY_X = 150;
var SHIP_VELOCITY_Y = 150;
// Global variables
var ship;
var planet;
var game = new Phaser.Game(GAME_WIDTH, GAME_HEIGHT, Phaser.AUTO, "game", {preload: preload, create: create, update: update});
function preload () {
game.load.image("ship", "sprites/phaser_ship.png");
game.load.image("planet", "sprites/planet.png");
}
function create () {
var ship = game.add.sprite(SHIP_X_POS, SHIP_Y_POS, "ship");
game.physics.arcade.enable(ship);
ship.body.velocity.x = SHIP_VELOCITY_X;
ship.body.velocity.y = SHIP_VELOCITY_Y;
var planet = game.add.sprite(PLANET_X_POS, PLANET_Y_POS, "planet");
game.physics.arcade.enable(planet);
planet.body.immovable = true;
game.physics.arcade.accelerateToObject(ship, planet, ACCELERATION_TOWARDS_PLANET);
}
function update () {
// nothing to update
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With