Search code examples
c#monogame

Monogame buttons


I have been trying to make a clicker game in monogame, But I can't figure out how to make a button. I've tried countless tutorials and none of them seem to work. What is the simplest way to make a button in monogame?


Solution

  • Drawing is usually done with a single function call assuming you want to simply draw a image into the screen without any shader(s) or magic stuff:

    _spriteBatch.Draw(ButtonTexture,ButtonRectangle,Color.White);
    

    this assumes _spriteBatch is defined in your game class, and that ButtonTexture (use Content.Load() to load a texture from the content pipeline) and ButtonRectangle are local variables that exist. Please consider the game's resolution so the ButtonRectangle variable should look like this

    ButtonRectangle = new Rectangle(ScreenX * 0.4,ScreenY*0.5,ScreenX * 0.1,ScreenY*0.1);
    

    For checking if the player has clicked the button you'd use

    MouseState mouse = Mouse.GetState();
    if(ButtonRectangle.Contains(mouse.Position) && mouse.LeftButton == ButtonState.Pressed)
    {
    //do stuff
    }
    

    Of course, there can be some stuff added, like using two click states to prevent the button being pressed every Update() call from your Game class. Or checking if the button is hovered and changing the sprite.

    At this point, there are also few UI libraries for Monogame like Myra.

    Knowing that you already looked in dozens of tutorials, you may want to use game engine, like Unity, GameMaker, etc.