Nick M
Nick M

Reputation: 3

XNA Rectangle Intersection issues

I am fairly new at XNA and I have come across a problem. I have a button class which I am using for a button on the start screen of the game. I want to make it so that when the mouse clicks on the button, a boolean isClicked is set to true and then you can do whatever you want with the button. However, when I compile the game it seems that I can't just click directly on the button's rectangle(or where it should be) but I have to click either below or above it, which changes each time I run the game.

I have this code for the button class:

class cButton
{
    Texture2D texture;
    public Vector2 position;
    public Rectangle rectangle;
    public Rectangle mouseRectangle;
    public Vector2 mousePosition;





    public cButton(Texture2D newTexture, Vector2 newPosition)
    {
        texture = newTexture;
        position = newPosition;






        rectangle = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
    }

    bool down;
    public bool isClicked;

    public void Update(MouseState mouse, GameTime gameTime)
    {




        mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);
        mousePosition = new Vector2(mouse.X, mouse.Y);
        if (mouseRectangle.Intersects(rectangle))
        {    
            if (mouse.LeftButton == ButtonState.Pressed)// if mouse is on button
            {
                isClicked = true;
            }
            else 
            {                   
                isClicked = false;
            }
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, color);
    }
}

}

And this code in the game 1 class for drawing that button:

        protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        switch (CurrentGameState)
        {
            case GameState.MainMenu:
                spriteBatch.Begin();
                spriteBatch.Draw(Content.Load<Texture2D>("Backgrounds/title"), new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
                btnPlay.Draw(spriteBatch);


                spriteBatch.End(); 
                break;


        }
        base.Draw(gameTime);
    }

I was thinking that it might have something to do with the screen resolution that I set for it, the code for that is here:

    //Screen Adjustments
    public int screenWidth = 1280, screenHeight = 720; 

        graphics.PreferredBackBufferWidth = screenWidth;
        graphics.PreferredBackBufferHeight = screenHeight;

Please help, I have no idea what I did wrong.

Upvotes: 0

Views: 1241

Answers (1)

Daniel Szekely
Daniel Szekely

Reputation: 31

I believe this question ought to help you out. :)

Basically, you create a point struct, and in the rectangle of the button you call the Contains method. It will tell you if the click is on the button.

Upvotes: 1

Related Questions