Question

I just play around with XNA and when I wanted to click on a sprite and something happen, I put this code:

if(Mouse.GetState().LeftButton == ButtonState.Pressed)

{

        if (sprite.Bounds.Contains(Mouse.GetState().X, Mouse.GetState().Y))
          {
              this.Exit();
          }
}

how ever when I hover over the sprite with my mouse and click nothing happens, why?

And how do I fix this?

If this helps I wrote my 2D sprite in a rectangle

No correct solution

OTHER TIPS

Texture.Bounds does not put the rectangle in the texture's place, the values of X and Y are both equal to 0.

You would have create your own rectangle to do .Contains() on based on your SpriteBatch.Draw() inputs.

enter image description here

The texture "logoTexture" is somewhere near the bottom left corner of the screen.

Please confirm that Bounds is calculated as such:

public Rectangle Bounds
{
    get
    {
        return new Rectangle(position.X - width / 2, position.Y - height / 2, width, height);
    }
}

I also suggest getting a reference to Mouse.GetState() a single time per update instead of calling it as needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top