I created an image of a button and displayed it on my screen. When someone presses and then releases the button, I then want a block of code to be executed.
My code works great because the code within if block below is only executed once.
Because, as the logic indicates the touch location contains the area touched and the users finger has released the button pressed/touched. Is this okay, to check the State of touch location released like in the logic below?
public Rectangle myButton
{
get { return myButtonRectangle; } // Getter
set { myButtonRectangle = value;}
}
if (myButtonRectangle.Contains(touchPosition) && touchLocation.State == TouchLocationState.Released)
{
// Code to execute when button is pressed goes here.
I would recommend creating a Button class with properties such as:
Rectangle area
String text
Color color
etc
and internal methods that draw the button correctly with the centered name and all.
Haven’t worked with touch, but I need to point out that if your buttons belong to an UI that is on top of your gameplay area that also takes touch input, you need to consume the touch event first with any UI buttons that are on top, otherwise you’ll execute your button code AND affect the gameplay area.
Check out Button right from MonoGame tests that some nice person had written a while ago. In fact that entire folder has some nice gems that are independent from iOS even though it resides in iOS folder there.