• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GML Efficient 'mouse in sprite' script

MeBoingus

Member
Howdy all,

Often times I'll draw a sprite to the screen, and need to detect whether or not the mouse is 'inside' of it.
I normally use 'point_in_rectangle' for this, but the obviously this won't work for sprites with a precise collision mask.

Take this sprite, for example:

ExampleSpr.png


My goal is to run some code if the mouse is inside of the sprite, using a precise mask.
The only script/method I can think of that achieves this is:

Code:
///mouse_in_sprite(sprite, x, y);

var tempO = instance_create(argument1, argument2, obj_mousein);
tempO.sprite_index = argument0;


if (position_meeting(mouse_x, mouse_y, tempO))
{
    with (tempO) { instance_destroy(); }
    return true;
}

with (tempO) { instance_destroy(); }
return false;

However, (obviously) creating and destroying an instance constantly (this code runs in the draw event, as we are drawing the sprite to the screen) is HORRIBLY inefficient.


Does anyone know of a better way to handle this?
Warm regards :).
 

TheouAegis

Member
Will these always be built-in/included sprites? If so, write up a quick little program to store the alphas of each pixel to a buffer and then save that buffer to a file. Include the file with your project.

When you draw a sprite and need it traced, take the mouse coordinates relative to the sprite's top-left corner and condense the two values down to a single value. Then load the file for that sprite and check if the alpha at the value for the mouse position is not 0.
 

YellowAfterlife

ᴏɴʟɪɴᴇ ᴍᴜʟᴛɪᴘʟᴀʏᴇʀ
Forum Staff
Moderator
You can reuse a single instance of that special invisible object (creating it if there isn't one yet) - no need to create-destroy it.
 
Top