FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Learn JavaScript with Phaser

Game Mechanic: Smaller Sprite Collision Boxes

We can play with collision effects with body size of player / enemy which can make the game seem fairer and more forgiving for players. This can really help if you are designing levels that are hard and of the shape of your sprite animations sometimes creates a big box area.

https://phaser.io/examples/v2/arcade-physics/offset-bounding-box

 

 

Check the Code: what we need to know and do

Our mechanic relies on us being able to check if we are jumping on our enemy. We will do this by checking to see if our player is on the way up or coming down from a jump. To do this we'll need to know about the following game elements;

The code for a minimal example of the Smaller Sprite Collision Boxes game mechanic is shown here -  https://game-mechanic-smaller-sprite-collision-boxes.glitch.me/

Going over the code:

The size of or player is when we add it 46 wide by 42 high.

Have a look at an updated create function for the code that alters the collision body box of the player.

    player.body.setSize(26, 37, 5, 5);

There are four parameter here setSize(width, height, offsetX, offsetY) . We can see that we have set a new height and width of the Body of this sprite. In this case we taken 10 pixels off each. This does not affect how it look but does affect when it collides with other sprites.

If we don't put in the offset values for example if we use the follwoing code.

    player.body.setSize(26, 37, 0, 0);

then that new body will be anchored at the top left.


This is not ideal also. You may also notice that they player sinks into the ground.

So let's rese

To make this more useful to us as game designer we centered this new collision box by using the offset values 5 and 5. In other word this shifted the box 5 px over to the right (+5x) and five down (+5y) .


Our player no longer sinks into the ground and the new collision box seems more fair.

Collision boxes and Hazards

In the code example above the same technique has been applied to the enemy, but in this case the collision box has been set to be in the bottom right of the spider to make it very easy to jump over.

It's probably too easy! Have a play to make this seem a bit more of a challenge.

That's it. We hope you enjoy adding this game dynamic.

Bonus read: you can have a look at this great article on the more advanced ways of creating 2D platform games 1.

http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/ ^

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.