By jlnr (dev)
Date 2013-07-08 09:22
Images have no position, they are only a (part of a) texture in memory. You are right that you'll have to loop all over an array of things that can be clicked, which you'll have to maintain yourself. I don't think it's particularly hairy in Ruby :)
The one thing that can be tricky is to have pixel-perfect collision detection when clicking on things, but bounding boxes are good enough for most uses. When they're not, you might have to keep a copy of the Image#to_blob
result around and use that to do hit-testing.
Unfortunatelly there is no simple method of using a mouse. Though I made a small Mouse class for my game to make it somewhat simpler. Main part of it is these two methods:
def over?(x,y,w,h)
if @x >= x and @x <= x+w and @y >= y and @y <= y+h then
return true
else
return false
end
end
def over_circle?(x,y,r)
dist = Math.sqrt((x - @x) ** 2 + (y - @y) ** 2)
if dist <= r then
return true
else
return false
end
end
As I keep mouse in global variable $mouse, whenever I must check if mouse is over a particular part of menu, I just use code:
do_something if $mouse.over?(x, y, width, height)
Works the way it should most of the times.
That's pretty nice, especially the over_circle.
By jlnr (dev)
Date 2013-07-08 16:13
Nitpick: This is very unlikely to ever be a performance problem, but you can get rid of the Math.sqrt
call and just compare dist <= r*r
instead :)
And you can directly return the result of comparisons without an if
block:
def over?(x,y,w,h)
@x >= x and @x <= x+w and @y >= y and @y <= y+h
end
As for the second one, I know that (well, didn't know that I can skip return
), but sometimes I prefer to have things a bit clearer. Old habits die hard :p
Isn't this math thing the same as Gosu.distance
?
Just checked, and it actually is. I completely forgot about that method!