Ch013 - Game Mechanic: Smaller Sprite Collision Boxes

Ch013 - Game Mechanic: Smaller Sprite Collision Boxes

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.

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;

Going over the code:

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/

The size of or player is when we add it in the example above is 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. The following code is added after the player is added to the game.

    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 following 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 reset this. 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

The same technique can be applied to an enemy. The collision box has been set to be in the bottom right of the hazard to make it very easy to jump over from left to right..

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.