Touching an object in Monkey X

I’ll share here something that is related to a project I’m working on.

How to test if the user/player has touched an object on the screen. In our example program the object is the following (you may download the object):

ball

My little code tests if object is touched while it moves around the screen. The test is pixel accurate.

The idea is to use a databuffer where the image’s pixel data is stored as integers, which is done by using the LoadImageData command. Each pixel takes 4 bytes of space in the buffer.

The alpha component is set to zero; the remaining bits represent the RGB values. Each integer is stored in variable data. If data <> 0 then the player has touched the object. Only the pixel of the image that has been touched, will be tested.

The code below clarifies this:

This code can’t be compiled to HTML5 target, so you’ll have to try this code in Monkey yourself to see how it works. In free Monkey X this can be compiled to desktop, in Monkey X Pro the code can have also Android target.

Feel free to use this code!

Updated 3/8/2016

Below is a bit more advanced code, where you can use an image where the background color isn’t transparent.

You may download the ball2.png file used in the code (the image has white background color):

ball2

The code masks the image with given mask color in function MaskImage, in the example mask color is 255,255,255.

Updated to handle scaled graphics.

Feel free to improve and use the codes above!

Below is a video demonstration of the code above: