Setting a Circle for collision detection in phaser 2
In this post on phaser 2 I will be writing about using the body.setCircle method to make the collision detection work with a circle shape rather than the default square shape. For many phaser 2 powered games the default square shape works just fine, but for other games that involve ball shaped display objects it is necessary to set the physics body shape to that of a circle. The reason being that by doing so when a ball like object hits another at an angle it will bounce as expected of a ball shaped object rather than a square.
1 - What to know before continuing.
This is a post on setting the shape of a physics body when making a phaser 2 game project. It is not a getting started post with physics in phaser, let alone with javaScript in general.
1.1 - This is a phaser 2 post
In this post I was using phaser 2.11.1 of phaser the javaScript powered game framework. So the code examples here will likely break in the newer phaser 3 or later.
2 - The setCircle example
For this example I have two sprites one positioned at the center of the game world, and another positioned at a 45 degree angle away from the ball sprite at the center. I enable physics for both sprites, and have the ball positioned away from the one at the center move in the direction of the one at the center. When the ball hits the ball at the center the ball at the center continues to move in the same direction as exspected, rather than what happens if the body.setCircel method is not used.
2.1 - My createBall method that uses body.setCircle
Here I call the setCircle method of the physics body of a physics enabled sprite. If I do not need to do anything with an offset I only need to pass the radius of the size of the circle as the first argument.
|
|
2.2 - Create a Sheet for the balls
Here I create a sprite sheet for the balls using a canvas solution.
|
|
2.3 - Phaser.Game
|
|