Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
Detecting "touch" on box2d body — Gideros Forum

Detecting "touch" on box2d body

arjunr24724arjunr24724 Member
edited February 2013 in Game & application design
I have been trying to use the queryAABB method to create a fixture on the touch/mouse coordinate to detect which body (randomly spawning, active and moving, 32x32) has been touched.

local function onTouchesBegin(event)
local x = event.touch.x
local y = event.touch.y
local fixtures = thisLevel.B2_Worlds[1]:queryAABB(x - 0.00005, y - 0.00005, x + 0.00005, y + 0.00005)
if #fixtures > 0 then
local body = fixtures[1]:getBody()
print("Begins: Touched something!")
end
end

However, this doesn't seem to yield consistent results. Sometimes I get #fixtures>0, most times I don't. Changing queryAABB size doesn't really affect the outcome. I want to avoid Sprite hit-detection.

Any ideas?

Comments

  • nvm

    for those who need to know, don't forget to use stage:globalToLocal(x,y) on the returned event's coordinates.
  • atilimatilim Maintainer
    Accepted Answer
    This simple code works fine. I hope it helps understanding what's wrong on your side:
    require "box2d"
     
    local world = b2.World.new(0, 0)
     
    local function createBox(x, y, w, h, name)
    	local shape = b2.PolygonShape.new()
    	shape:setAsBox(w, h)
     
    	local body = world:createBody{type = b2.STATIC_BODY, position = {x = x, y = y}}	
    	body:createFixture{shape = shape}
     
    	body.name = name
     
    	return body
    end
     
    for i=1,20 do
    	createBox(math.random(0, 320), math.random(0, 480), 30, 20, "box "..i)
    end
     
    local function onTouchesBegin(event)
    	local x = event.touch.x
    	local y = event.touch.y
    	local fixtures = world:queryAABB(x - 0.00005, y - 0.00005, x + 0.00005, y + 0.00005)
    	if #fixtures > 0 then
    		local body = fixtures[1]:getBody()
    		print("touched "..body.name)
    	end
    end
     
    stage:addEventListener(Event.TOUCHES_BEGIN, onTouchesBegin)
     
    local debugDraw = b2.DebugDraw.new()
    world:setDebugDraw(debugDraw)
    stage:addChild(debugDraw)
  • Thanks. I used pretty much the same code. Except, I had to use stage:globalToLocal(event.x, event.y) when onTouchesBegin() was called to get the correct coordinates. Other than that, queryAABB worked exactly as it should.

    I am using TiledAsWorldEditor class to manage the world. Maybe thats why.
Sign In or Register to comment.