我试图在模拟器上检测动态对象与静态对象的碰撞,但不能在设备上检测。
在createScene上我创建了对象:
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 )
听众:
local function onCollision( event )
if ( event.phase == "began" ) then
gameOver()
elseif ( event.phase == "ended" ) then
end
end
函数gameOver()从未调用过设备。
请帮忙吗?
答案 0 :(得分:1)
您需要物理,然后在添加物理实体之前调用physics.start()
。并且你的物理实体必须对齐,以便它们实际碰撞。这里修改了代码:
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 )
我还添加了您可能已经拥有的缺失函数,只是为了能够运行代码。请记住,playerBox
是一个传感器,因此不会发生碰撞反应,其他物体只会通过它。