The latest version of Pine-2K now supports collision detection between sprites. It does this using a simple collision declaration that is placed immediately before rendering a sprite and a function callback.
The format for the collision declaration is as follows:
io("COLLISION", spriteIdx, mask, callback_function);
In addition to setting up the call back function, this function allows you to assign an index for the sprite that is about to be rendered. This is specified via the `spriteIdx` parameter. Sprite indices can be any positive value other than zero and in the range of a normal 32-bit integer. Sprite indices do not have to be unique and it might be valid in your game to have all enemies or bullets have the same index. Examples for handling multiple enemies are shown below.
The mask
parameter specifies which other sprites you wish to test for collisions. It can be the index of another sprite, a mask that can be applied for a range of sprites or a zero to indicate no matching should occur. A mask value of -1 (which equates to the hex value of 0xFFFFFFFF) indicates that the sprite should be tested against all other sprites.
The collision detection relies on the order in which the sprites are rendered in a single frame - it is only possible to detect a collision with the sprite currently being rendered and those already rendered to the screen.
A simple scenario.
Let’s look at a simple example of a player and an enemy sprite traveling around the screen.
001 const ENEMY_IDX = 1;
002 const PLAYER_IDX = 2;
003
004 function collide() {
005 console("Houston we have a problem.");
006 }
007
008 // Render the enemy ..
009 io("COLLISION", ENEMY_IDX, 0);
010 sprite(enemyX, enemyY, enemyImg);
011
012 // Render the player ..
013 io("COLLISION", PLAYER_IDX, ENEMY_IDX, collide);
014 sprite(playerX, playerY, playerImg);
Breaking this down, line 009
declares that the next sprite rendered (the enemy on line 010
) will have a collision index of ENEMY_IDX
(or 1). You will note that there is no mask or callback function specified as this is the first sprite to be rendered in the current frame and hence there would be nothing to collide with!
After rendering the enemy sprite, we proceed to render the player. This time, at line 013
, we declare the upcoming sprite to have an index of PLAYER_IDX
(or 2) and that we are interested in detecting collisions with the enemy whose collision index is ENEMY_IDX
. If a collision is detected when rendering the sprite, the function collide()
will be called automatically.