I am wondering what the best way to make a button in MonoGame is. I tried to look for an answer but none seem to be out there. Is it bad practice to use WinForm buttons? If so, what viable alternatives exist?
Asked
Active
Viewed 9,756 times
3
-
Is it *bad practice*? It depends what you're trying to do. Is this a button for use in the game (e.g. a 'Play' button on the title screen) or are you trying to make some kind of level editor? – craftworkgames Sep 07 '15 at 04:36
-
@craftworkgames It would be for use in a game – Sep 07 '15 at 13:16
1 Answers
7
I always like making a custom button class, this gives me a lot of flexibility for creating creative buttons.
The class creates a button with a texture and a position x and position y and a unique name, after i've done that i'll check my mouse position and see if it's inside the button or not, if it is inside the button then it can click the button and it will search the button by name and execute the given command :)
Here is an example of my button class: (not the best way, but hey it works perfectly for me)
public class Button : GameObject
{
int buttonX, buttonY;
public int ButtonX
{
get
{
return buttonX;
}
}
public int ButtonY
{
get
{
return buttonY;
}
}
public Button(string name, Texture2D texture, int buttonX, int buttonY)
{
this.Name = name;
this.Texture = texture;
this.buttonX = buttonX;
this.buttonY = buttonY;
}
/**
* @return true: If a player enters the button with mouse
*/
public bool enterButton()
{
if (MouseInput.getMouseX() < buttonX + Texture.Width &&
MouseInput.getMouseX() > buttonX &&
MouseInput.getMouseY() < buttonY + Texture.Height &&
MouseInput.getMouseY() > buttonY)
{
return true;
}
return false;
}
public void Update(GameTime gameTime)
{
if (enterButton() && MouseInput.LastMouseState.LeftButton == ButtonState.Released && MouseInput.MouseState.LeftButton == ButtonState.Pressed)
{
switch (Name)
{
case "buy_normal_fish": //the name of the button
if (Player.Gold >= 10)
{
ScreenManager.addFriendly("normal_fish", new Vector2(100, 100), 100, -3, 10, 100);
Player.Gold -= 10;
}
break;
default:
break;
}
}
}
public void Draw()
{
Screens.ScreenManager.Sprites.Draw(Texture, new Rectangle((int)ButtonX, (int)ButtonY, Texture.Width, Texture.Height), Color.White);
}
}

Aintaro Mocrosoft
- 156
- 5