1

I'm attempting to determine which sprite a mouse is over in an isometric 2D game. I think my best bet is to draw each sprite a different color into a separate renderTarget2D and turn it into a Texture2D at which point I can get the color data from the mouse point and check it against the drawn sprites.

The problem I'm having with that method though is that I can't change the color of the individual sprites to a solid color. If I change the Color in the spriteBatch.Draw call, it only tints the color of the sprite rather than drawing it at a solid color so the data I retrieve from the Texture doesn't help.

Any suggestions or help with drawing those sprites in a solid color?

user1306322
  • 8,561
  • 18
  • 61
  • 122
Steve
  • 127
  • 3
  • 13

1 Answers1

6

Don't do it that way. Creating a new render target and copying the data into the memory even for a mere hundred sprites sixty times per sec is far beyond what current systems can handle.

Simply use the Contains method of the Rectangle structure:

var destination = new Rectangle(100, 100, 50, 50);
bool mouseOver = destination.Contains(mouseX, mouseY);
Lucius
  • 3,705
  • 2
  • 22
  • 41
  • I originally considered using Rectangle.Contains but there are too many situations where my sprites are overlapping. Also, since my sprites are isometric and irregularly shaped, the combination of layered sprites and random empty space between them causes Contain checks to return false positives. /n I've got a system in place that will limit the sprites drawn in the check to a range of around 10~20 per check. Maybe I'll take another crack at using some form of rectangles and just force the player to select near the center of the sprite they want to select – Steve Jan 31 '13 at 00:48
  • You can still use a [bounding polygon](http://stackoverflow.com/q/14581919/925580) to approximate the shape of the sprite. It will definitely be more efficient than going with a pixel based approach. If some sprites overlap and the mouse is on all of them, simply sort them by their z-value (depth) and take the frontmost. – Lucius Jan 31 '13 at 01:06
  • I went ahead and decided to go with Rectangle.Contains. I may run into some issues later on but for now it's getting the job done. Thanks for the help =) – Steve Jan 31 '13 at 07:34
  • While I agree in general that using bounding polygons is the way to go, if pixel-perfect collision is necessary you can theoretically do it on the GPU using occlusion queries, where supported. Shawn Hargreaves describes the technique here: http://blogs.msdn.com/b/shawnhar/archive/2008/12/31/pixel-perfect-collision-detection-using-gpu-occlusion-queries.aspx – Cole Campbell Jan 31 '13 at 16:16