Skip to content

Collisions

Zal0 edited this page Sep 13, 2021 · 4 revisions

Right now if you move the player you'll see it can go throught walls (also going offscreen will kill the sprite so we need to avoid this). Here is how to add collision checking with background tiles:

  • Collisionable tiles are declared as an array of UINT8 ended with 0. If you open the file tiles.gbr you will see that we only have two tiles (the first one is empty and we don't want that to be collidable). Declare the next array on StateGame.c
UINT8 collision_tiles[] = {1, 0};
  • This list is the 2nd paramater passed to the InitScroll function on the Start method of StateGame. Right now it is set to 0 (null), change it into this:
InitScroll(BANK(map), &map, collision_tiles, 0);
  • Now if you want the scroll to manage collisions with your sprite you need to use the function TranslateSprite instead of directly updating the x and y coordinates of the sprite. Here is how the Update method in your SpritePlayer should look like now:
void UPDATE() {
	if(KEY_PRESSED(J_UP)) {
		TranslateSprite(THIS, 0, -1);
		SetSpriteAnim(THIS, anim_walk, 15);
	} 
	if(KEY_PRESSED(J_DOWN)) {
		TranslateSprite(THIS, 0, 1);
		SetSpriteAnim(THIS, anim_walk, 15);
	}
	if(KEY_PRESSED(J_LEFT)) {
		TranslateSprite(THIS, -1, 0);
		SetSpriteAnim(THIS, anim_walk, 15);
	}
	if(KEY_PRESSED(J_RIGHT)) {
		TranslateSprite(THIS, 1, 0);
		SetSpriteAnim(THIS, anim_walk, 15);
	}
	if(keys == 0) {
		SetSpriteAnim(THIS, anim_idle, 15);
	}
}

There is still a small issue that can be fixed. Unless you did a square your Sprite might be stopping before touching the collidable tile

enter image description here

this can be fixed by adjusting the collider of the Sprite. In order to do this you need to open the meta file created for this sprite in res/sprites/player.gbr.meta with a text editor. By default you will see something like this:

-px 0 -py 0 -pw 16 -ph 16

These values define the collider of the Sprite. As you see the width is set to 16 but out sprite is a bit smaller. You need to change it into:

-px 2 -py 0 -pw 12 -ph 16
Clone this wiki locally