How to Click on an Object in Game Maker

The Game Maker game development suite from YoYo Games contains a wide variety of drag and drop functions for fast game design. However, the one function notably missing from the Game Maker prebuilt options is one that allows you to check if an object has been clicked on by the mouse and if it's able to perform operations if it was. This oversight can be easily addressed, however, with just a few lines of Game Maker's built-in scripting language, GML.

...
A missing game function is easily overcome with a few simple steps.

Step

Create a sprite by right-clicking Sprites and clicking "New Sprite". Click "Edit Sprite". Sprites are images designed to be used in your video game. Double click the thumbnail. This will open a "Paintshop"-like program called "Image Editor". Draw a fast circle and click the green check mark to save and close the dialogs.

Step

Create an object from that sprite by right-clicking "Objects" and clicking "New Object." Select "sprite0" as the sprite for this object from the list.

Step

Click "Add Event". Click "Mouse". Choose "Left Pressed."

Step

Now, every time the left-button on the mouse is clicked, every object with this event will run the code given.

Step

Click "Control". Drag the "execute a piece of code" icon, which looks like a pad of notebook paper, into the actions box. This will open the code editor.

Step

Paste the following into the code editor:

Step

d = point_distance(mouse_x, mouse_y, self.x + (self.sprite_width/2), self.y + (self.sprite_height)/2) if (d < self.sprite_width/2) { instance_destroy() }

Step

First, the object (and remember, this is for every object in the game) will check to see how far away it is from the mouse pointer and store that distance in a variable named "d".

Step

Second, if that distance is less than half the width of the sprite, it will destroy itself.

Step

Click the green check marks to get out of the code and event editors.

Step

Test. Right click on "Rooms" and choose "Create Room". Click a few times around the room to create some instances of your object. Click the green arrow to run your game. The circles should disappear whenever you click on them.