Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
BitmapX -- Bitmap class with pixel-perfect hit detection — Gideros Forum

BitmapX -- Bitmap class with pixel-perfect hit detection

n1cken1cke Maintainer
edited July 2016 in Code snippets
It's Bitmap-based class to detect mouse/touch hits with pixel-perfect accuracy for any shapes.
You use it exactly as Bitmap class, it just improves hit detection: hits will be detected only for pixels with alpha greater than 0.
Thanks to @chuz0 for idea: http://giderosmobile.com/forum/discussion/6556/another-use-of-rendertarget
BitmapX = Core.class(Bitmap)
 
function BitmapX:init(texture)
	local w, h = texture:getWidth(), texture:getHeight()
	if texture:getClass() ~= "RenderTarget" then
		self.renderTarget = RenderTarget.new(w, h)
		self.renderTarget:draw(self)
		self:setTexture(self.renderTarget)
	else
		self.renderTarget = texture
	end
	self.renderWidth, self.renderHeight = w, h
end
 
function BitmapX:hitTestPoint(x, y)
	local w, h = self.renderWidth, self.renderHeight
	x, y = x + 1, y + 1
	if x < 1 or y < 1 or x > w or y > h then return end
	local color, alpha = self.renderTarget:getPixel(x, y)
	if alpha > 0 then return true end
end
Example:
local texture = Texture.new "image.png"
local button = BitmapX.new(texture)
button:addEventListener(Event.MOUSE_DOWN, function(e)
	local x, y = button:globalToLocal(e.x, e.y)
	if button:hitTestPoint(x, y) then print "HIT" end
end)
stage:addChild(button)
button:setScale(2)
button:setRotation(30)
+1 -1 (+9 / -0 )Share on Facebook
Sign In or Register to comment.