Domanda

I'm trying to detect collision of a dynamic object with a static object, on simulator works, but not on device.

On createScene i create the objects:

b1 = display.newRect( 50, 80, 140, 140 )
b1:setFillColor( 49/255, 179/255, 173/255 )
b1.anchorX = 0.0
b1.anchorY = 0.0
physics.addBody( b1, "static", { density = 1.0, friction = 0.3, bounce = 0.2 }  )

b1:addEventListener( "collision", onCollision )  


playerBox = display.newRect( display.contentCenterX - 55, display.contentCenterY - 55, 110, 110 )
playerBox:setFillColor( 241/255, 76/255, 0/255 )
playerBox.anchorX = 0.0
playerBox.anchorY = 0.0
playerBox:addEventListener( "touch", onTouch )
physics.addBody( playerBox, "dynamic", { friction=0.3, isSensor=true } )

playerBox:addEventListener( "collision", onCollision )

group:insert( b1 )

group:insert( playerBox )

And on listener:

local function onCollision( event )
    if ( event.phase == "began" ) then
      gameOver() 
    elseif ( event.phase == "ended" ) then  
    end
end

Function gameOver() never called on device.

Please, any help?

È stato utile?

Soluzione

You need to require physics, then call physics.start() before adding physics bodies. And your physics bodies must be aligned so that they actually collide. fixed code here:

local physics = require("physics")
physics.start()

local group = display.newGroup()

local function onTouch()
    print("touched")
end

local function gameOver()
    print("gameover")
end

local function onCollision( event )
    if ( event.phase == "began" ) then
      gameOver() 
    elseif ( event.phase == "ended" ) then  
    end
end

b1 = display.newRect(  display.contentCenterX - 50,display.contentCenterY, 140, 140 )
b1:setFillColor( 49/255, 179/255, 173/255 )
b1.anchorX = 0.0
b1.anchorY = 0.0
physics.addBody( b1, "static", { density = 1.0, friction = 0.3, bounce = 0.2 }  )
b1:addEventListener( "collision", onCollision )  

playerBox = display.newRect( display.contentCenterX - 55, display.contentCenterY - 150, 110, 110 )
playerBox:setFillColor( 241/255, 76/255, 0/255 )
playerBox.anchorX = 0.0
playerBox.anchorY = 0.0
playerBox:addEventListener( "touch", onTouch )
physics.addBody( playerBox, "dynamic", { friction=0.3, isSensor=true } )

playerBox:addEventListener( "collision", onCollision )

group:insert( b1 )

group:insert( playerBox )

I also added missing functions which you might probably already have, just to be able to run the code. Remember that playerBox is a sensor so there will be no collision reaction, other bodies will just pass through it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top