Playing with gravity in phaser ce
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.
1 - What to know before continuing.
1.1 - This is a phase ce 2.x post
In this post I am using phaser Community Edition 2.11.1 of phaser
2 - Two or more Balls in a group
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.
2.1 - The update Gravity method
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.
2.2 - The make ball helper
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.
2.3 - The create Ball Group helper
Here Is the method that creates the group of balls.
2.4 - Create a Ball sprite sheet with canvas
Here I have a simple helper that makes a sprite sheet for the balls using the 2d canvas drawing context.
2.5 - Phaser.Game
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.
3 - Conclusion
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.