Not logged inGosu Forums
Forum back to Help Search Register Login
Up Topic Gosu / Gosu Exchange / Mouse click detection for overlapping sprites
- - By psylem Date 2012-04-29 12:28
Has anyone got any tips or know of a good library to determine what is being clicked on when you have a bunch of sprites that may be overlapping one another? My sprites are groovy retro looking gifs with transparency at the moment, so the edge is nice and pixelated if that helps.
Parent - - By Trebor777 Date 2012-04-29 15:16
One acronym : AABB
Parent - By erisdiscord Date 2012-04-30 00:23
I think what OP wants is hit testing that takes transparency into account. I assume they're getting hits on the "wrong" sprite (i.e., not the one it looks like they're clicking) when the transparent region of one is overlapping a non-transparent region of another.

OP: Once you've found your candidates by the usual bounding box method, you'll need to figure out some other way of querying the transparent regions. One way would be to build a bitmask based on the alpha channel and test that. You can get the raw image data by calling Image#to_blob.
Parent - - By erisdiscord Date 2012-04-30 00:38 Edited 2012-04-30 00:52
Here's a magic incantation that returns an array of boolean values for each pixel. true means the pixel has an alpha of over 50%.

mask = image.to_blob.unpack('L>*').map{|x| (x & 0xff) >= 0x80 }.join(' ')

The array is flat, so index with mask[x + y * image.width]. This is also a very inefficient way to store this information (one pointer to a Ruby object per pixel, plus whatever overhead an Array has), but I'll leave improving on it as an exercise for you. :D

Alternatively, you can use TexPlay, which adds a get_pixel(x, y) method (along with several drawing methods and lots of other nifty image manipulation fun that you probably won't need) and test the transparency that way.

require 'texplay'
class Gosu::Image
  def solid? (x, y); (get_pixel(x, y) & 0xff) >= 0x80; end

I'm not sure what the implications are for performance if you do it that way, but it's a lot easier.
Parent - - By psylem Date 2012-04-30 12:35
Thanks erisdiscord, that looks like what I need.
Parent - By erisdiscord Date 2012-04-30 17:41
Yeah, I think I might have got the bitmask wrong though for the Texplay example! I think the color Texplay returns is ARGB, not RGBA, so it would really be get_pixel(x, y) >> 24 & 0xff.
Up Topic Gosu / Gosu Exchange / Mouse click detection for overlapping sprites

Powered by mwForum 2.29.7 © 1999-2015 Markus Wichitill