As of late I am diving into expanding my content on phaser ce and have gotten into the arcade physics engine. Todays post will be on gravity, setting values for gravity is pretty straight forward if you just want to have all objects be pulled down to the ground. In that case all that is required is to set the sprite.body.gravity.y property to a desired value. However with other projects it can get a little complicated, so I have started this post for outlining some use case examples of gravity in phaser ce.
In this post I am using phaser Community Edition 2.11.1 of phaser
For this example I have two balls and I want them to attract together depending on there distance from each other. So for this example I will want to work out some kind of method where the gravity property is changed on every frame tick.
Here is the update gravity method that I worked out. I just start by making sure that the gravity properties for each ball are set to zero for starters. Then I go threw each ball and add to there gravity properties based on the distance and angle to each other.
Here I have a simple helper where I am just creating a single ball sprite and returning it. I enable physics for the ball here, and this method will be used by another that will create the group of balls.
Here Is the method that creates the group of balls.
Here I have a simple helper that makes a sprite sheet for the balls using the 2d canvas drawing context.
Now it is time to make it all work with a Phaser.Game instance and a state object. In the create method I call my createBallSheet, and CreateBall group methods, and call the updateGravity method in the update method as it must be called on each frame tick.
When I start this project the balls do act as expected as they end up moving to each other.
Just touching base on this topic for now with this one example. If I continue investing more time into these phaser posts I might come around to update and expand this in the not to distance future.