HT Games

GameMaker Studio 2: Spawn Objects on Mouse Click Anywhere in the Room

Here's how to create an instance of an object at the mouse position when the player clicks anywhere in the room using GameMaker Studio 2 (GML).

1. Set Up the Event

Open your object's Event Editor. Add a Mouse > Left Pressed event (or Right Pressed for right-click).

2. The Code (GML)

// Ensure click is within room boundaries
if (mouse_x >= 0 && mouse_x <= room_width && mouse_y >= 0 && mouse_y <= room_height) {
    // Create instance at mouse coordinates on the "Instances" layer
    instance_create_layer(mouse_x, mouse_y, "Instances", obj_YourObject);
}

Code Explanation

  • mouse_x, mouse_y: Built-in variables for current cursor position.
  • room_width, room_height: Current room dimensions. The if check prevents errors if the mouse is technically outside the room view.
  • instance_create_layer(x, y, layer, object): Spawns the object. Replace obj_YourObject with your actual object name. Ensure the layer name ("Instances") matches your room setup.

Preventing Multiple Spawns (Single Click Only)

Use a variable flag to allow only one creation:

// Create Event: Initialize flag
can_spawn = true;

// Left Pressed Event
if (can_spawn) {
    if (mouse_x >= 0 && mouse_x <= room_width && mouse_y >= 0 && mouse_y <= room_height) {
        instance_create_layer(mouse_x, mouse_y, "Instances", obj_YourObject);
        can_spawn = false; // Disable further spawns
    }
}

Additional Options

  • Right Click: Use the Right Pressed event instead.
  • Limit Quantity: Check instance_number(obj_YourObject) < max_limit before spawning.
  • Visual Effects: Add a fade-in animation or particle system in the created object's Create Event for polish.

https://www.htfbw.com © HT Games