0
\$\begingroup\$

How do I detect if my mouse if hovering over a specific sprite?

For example I'm making a custom button and I want to check if my mouse is hovering over it so I can make animations.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You need two things:

  1. Get the position of the mouse cursor
  2. Get the position and size of your sprite texture (Texture2d has a very handy propery that does just that)

The second point depends of your implementation but you could have a Sprite class that holds a reference to a Texture2d and a Vector2 for the position.

The Bounds property of Texture2 returns a Rectangle which has a Contains method that does exactly what we need. So from here we can write a very simple function that returns true when a point is located within a given sprite.

bool IsPointOverSprite(float x, float y, Sprite sprite)
{
    return (sprite.getTexture().getBounds().Contains(pos.X, pos.Y);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Be aware that the Bounds property only gives you a width and height in the rectangle, as textures don't have an origin location. getBounds() in this context will be retrieving the Bounds property and combining it with your sprite's location. \$\endgroup\$ Commented Mar 18, 2016 at 13:43

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.