Search code examples
game-maker

Simple Button using DRAW GUI in GameMaker


This is my button under DRAW GUI.

if point_in_rectangle(window_mouse_get_x(),window_mouse_get_y(),790,317,943,385)
{ var hover=1; } else { var hover=0; }
draw_sprite(spr_mainmenu_smallbutton,hover,865,360);
if (distance_to_point(mouse_x,mouse_y)<=0)
{
if mouse_check_button(mb_left)
draw_sprite(spr_mainmenu_smallbutton,2,865,360); 
}
draw_set_color(make_colour_rgb(163,190,240));
draw_set_font(fnt_mainmenu_text);
draw_text(865,350,"New  Game");

Fairly simple. It draws a rectangle and the text "New Game" on it. When the mouse hovers over it, it lights up. When you click it, the graphic changes. It's a good button.

The problem occurs when I enter the area of the button while HOLDING the mouse button.

enter image description here

See how it behaves? Instead of lighting up, it gets pressed.

All because I am holding the mouse button as I come in. Any way to avoid this and have it light up instead?


Solution

  • You need use mouse_check_button_pressed() instead mouse_check_button(). Something like this:

    Create event:

    button_pressed = false;
    mouse_over = false;
    
    button_x = 865;
    button_y = 350;
    button_width = 153;
    button_height = 68;
    
    button_left = button_x - button_width div 2;
    button_right = button_left + button_width - 1;
    button_top = button_y - button_height div 2;
    button_bottom = button_top + button_height - 1;
    

    Step end event:

    mouse_over = point_in_rectangle(device_mouse_x_to_gui(0), device_mouse_y_to_gui(0), button_left, button_top, button_right, button_bottom);
    
    if !mouse_over
        button_pressed = false;
    else
    {
        if mouse_check_button_pressed(mb_left)
        {
            button_pressed = true;
        }
        else if mouse_check_button_released(mb_left) and button_pressed
        {
            // action
            show_message("pressed");
        }
    }
    

    Draw GUI event:

    if button_pressed
        draw_sprite(sprite_index, 0, button_x, button_y);
    else if mouse_over
        draw_sprite(sprite_index, 1, button_x, button_y);
    else
        draw_sprite(sprite_index, 2, button_x, button_y);