Hitting a sprite

When checking whether a user has hit or clicked on a sprite there are two options:

This example takes a closer look at the second option: GetSpriteHit. This command is particularly useful for a situation where you quickly want to find what sprite a user has touched or clicked on. Internally this command will check all sprites within the area and return the appropriate ID number. It's a great time saver and means you don't need to be cycling through and checking specific sprites.

Two sprites will be placed side by side and when the user clicks or hits them the ID number of that sprite will appear on screen.

Getting started

The initial set up code sets a virtual resolution of 320 x 480, this is followed by loading the images "chip5.png" and "chip25.png".


A sprite on the left uses "chip5.png", while a sprite on the right uses "chip25.png":

SetVirtualResolution ( 320, 480 )

LoadImage ( 1, "chip5.png" ) LoadImage ( 2, "chip25.png" )
CreateSprite ( 1, 1 ) CreateSprite ( 2, 2 )
SetSpritePosition ( 1, 100, 50 ) SetSpritePosition ( 2, 200, 50 )

Hitting a sprite

Within our main loop an if statement is used to determine when the user hits or touches the screen, at this point GetSpriteHit is called. The command takes two parameters - an X and Y location, which for our purposes will be the location of the input. The return value is an ID number for whatever sprite was hit, this gets stored in a variable that is printed out on screen:

do
    Print ( "Clicked on sprite" )
    Print ( sprite )

if ( GetPointerPressed ( ) = 1 ) sprite = GetSpriteHit ( GetPointerX ( ), GetPointerY ( ) ) endif
Sync ( ) loop

Whenever a user clicks or touches the screen the ID number of whatever sprite they were hitting will be displayed on screen. If no collision occurred then a value of 0 is returned from the command GetSpriteHit.

Full code listing

The final code listing is:

SetVirtualResolution ( 320, 480 )

backdrop = CreateSprite ( LoadImage ( "background4.jpg" ) ) SetSpriteColorAlpha ( backdrop, 200 )
LoadImage ( 1, "chip5.png" ) LoadImage ( 2, "chip25.png" )
CreateSprite ( 1, 1 ) CreateSprite ( 2, 2 )
SetSpritePosition ( 1, 100, 50 ) SetSpritePosition ( 2, 200, 50 )
do Print ( "Clicked on sprite" ) Print ( sprite )
if ( GetPointerPressed ( ) = 1 ) sprite = GetSpriteHit ( GetPointerX ( ), GetPointerY ( ) ) endif
Sync ( ) loop

Conclusion

The command GetSpriteHit is particularly useful for scenarios when numerous sprites are on screen. If you had a screen with 20 buttons on and wanted to know which one had been clicked, then all it will take is one call to GetSpriteHit. This is much more efficient than running through a loop and checking sprites individually.