GML Help with mouse buttons code



Help with mouse buttons code. I'm making a starting scree for my game and I want the player to be able to select with his left mouse button and can go to different rooms (such as options, two players, chaos mode, etc.). How would I do it? What would be the code?

Thanks a lot :)


If the menu options are individual objects then use the usual room_goto function in a mouse left pressed event.

If the menu options are not objects, just text drawn to the screen then you will need a controlling object to first detect if the mouse button is pressed globally and second if the mouse x and mouse y has coordinates that would mean it is over a menu option.

Phil Strahl

If you want a very simple solution, create sprites with the text and use them as sprites with a collision mask (so essentially making a button). Then you only check if a mouse_check_button_pressed(mb_left) happened, check the mouse coordinates, and then switch rooms accordingly.

Here's a simple example:
Let's assume you have a sprite that looks like this, spr_button_start

and another, spr_button_options

We could also implement them as sub-images but I keep things very simple here.

So you make a new object and title it obj_button_start and give it spr_button_start as sprite.
In the Create event, let's do this:
target_room = room_options // put here the options room
And in the Step event we check if the player clicked it
if (mouse_check_button_released(mb_left))
  var mouse_on_button = collision_point(mouse_x, mouse_y, obj_button_start, false, false)
  if (mouse_on_button)
Now duplicate the object, name it obj_button_options, switch the sprite to spr_button_options and the only thing you need to change now is the target_room in the Create event.

Of course, there are a lot of ways to do this, e.g. have a menu controller object that creates the buttons for you, so you don't have to place the button objects in the room. Or have the individual button objects inherit from a parent object, or just have one button object that executes a script, etc.