Making a Sprite physics body immovable in phaser ce
When working out things with physics in phaser ce there may be a need to set some display objects as immovable when hit by another display object physics body. So that is to not make it so the display object is immovable at all, just immovable when hot by another object.
1 - What to know before continuing.
This is a post on making display objects not move when hit by another display object when working out physics for a game made with phaser ce as a game framework. This is not a getting started post with physics in phaser ce or with phaser ce in general. In this post I am using many aspects of the framework that you should know a thing or two about before hand.
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 - An example of body.immovable
For this example I made a quick project that involves an immovable sprite that is placed at the center of the game world, and a bunch of sprites that move around the rest of the screen wrapping back around when the leave the bounds of the game world, and of course bounce off the immovable object when they hit it.
2.1 - making an immovable sprite
Here I have a helper method that will be used to make the immovable sprite. When I call this it will add the sprite to a game.data object that I create in the state object later. Making a sprite immovable is as simple as just setting the body.immovable boolean to true after physics have been enabled for the sprite.
|
|
2.2 - Making a group of sprites
Here I have a method that will be used to create a group of sprites.
|
|
2.3 - Making a sprite sheet with canvas
Here I have a method that will add a simple sprite sheet using canvas as a way to do so rather than bothering with an external sprite sheet.
|
|
2.4 - The Phaser.game instance
Now it is time to pull it all together with a Phaser.game instance and a state object. Here I create the sprite sheet, the immovable sprite, and the group of sprites in the create method of the single state object. In the update method I check for collision for each moving sprite in the group to set if a sprite hit the immovable sprite of another sprite.
|
|
3 - Conclusion
Setting a sprite as immovable is a fairly straight forward process of just setting the proper boolean in the body object true. No not let the immovable name of the property fool you though, and immovable sprite can still be moved as well. For example if making a breakout clone the paddle, and the blocks are examples of physics enabled sprites that I would want to set as being immovable. I hope you enjoyed this post on phaser ce, if you have any questions or concerns let me know in the comments, and thank you for reading.