Collision with zones

Description

It's possible to determine whether two sprites have collided by using the command GetSpriteCollision. But what happens if you wanted to check whether a sprite has entered a specific area on screen? This is where two specific commands come into play:

These two commands allow you to perform collision checks between a sprite and an area. This is particularly useful for many situations e.g. checking whether a player has crossed a race line or finding out if a player is within a heal zone that restores health.

In this example a sprite will move across the screen and be tested for entering an invisible box. When this event is triggered the sprite will have its color changed to green.

Overview

The process involved is as follows:

Within the main loop:

Creating a sprite

An image is loaded, followed with a call to create a sprite and set its position:

LoadImage ( 1, "peach.png" )
CreateSprite ( 1, 1 )
SetSpritePosition ( 1, 0, 0 )

Main loop

The first step within our main loop is to move the sprite over to the right of the screen. This is handled with a call to the command SetSpriteX:

SetSpriteX ( 1, GetSpriteX ( 1 ) + 1 )

The next part deals with checking when the sprite enters an invisible box. The commnd GetSpriteInBox is called. This command has five parameters:

It works by taking an ID number of the sprite you are checking, followed by several parameters that define the location of the collision box. With this line of code sprite 1 is checked (our crate) against a box that has its top left as 200, 0 and its bottom right as 300, 50:

if GetSpriteInBox ( 1, 200, 0, 300, 50 )

endif

As soon as our sprite enters this box our collision event will be triggered and the sprite can be turned green:

SetSpriteColor ( 1, 0, 255, 0, 255 )

All that's left in the main loop is a call to Sync to ensure the screen is updated:

Sync ( )

Full code listing

Everything is now in place. Here's the final code for our program:

SetVirtualResolution ( 320, 480 )

CreateSprite ( LoadImage ( "background6.jpg" ) )
LoadImage ( 1, "peach.png" ) CreateSprite ( 1, 1 ) SetSpritePosition ( 1, 0, 0 )
do SetSpriteX ( 1, GetSpriteX ( 1 ) + 1 )
if GetSpriteInBox ( 1, 200, 0, 300, 50 ) SetSpriteColor ( 1, 0, 255, 0, 255 ) endif
Sync ( ) loop

Conclusion

This example has demonstrated the use of the command GetSpriteInBox. This command along with GetSpriteInCircle is useful for a wide variety of scenarios.