这真的取决于你如何设置你的课程。您可能需要发布更多代码。我创建了这个示例,它按预期工作:
盒子.lua
local Box = {}
local physics = require("physics")
function Box:new()
local box = display.newRect(math.random(0,display.contentWidth),math.random(0,display.contentHeight),100,100)
physics.addBody(box)
local function onTouch(event)
if(event.phase == "began") then
display.getCurrentStage():setFocus(event.target)
elseif(event.phase == "moved") then
event.target.x = event.x
event.target.y = event.y
elseif(event.phase == "ended") then
display.getCurrentStage():setFocus(nil)
end
end
box:addEventListener("touch", onTouch)
return box
end
return Box
主程序.lua
local physics = require("physics")
physics:start()
physics.setGravity(0,0)
local box1 = require("box"):new()
box1.myName = "box 1"
local box2 = require("box"):new()
box2.myName = "box 2"
local function onGlobalCollision (event)
if ( event.phase == "began" ) then
print( "began: " .. event.object1.myName .. " & " .. event.object2.myName )
end
end
Runtime:addEventListener( "collision", onGlobalCollision )
我很确定你甚至可以完全从 main 中删除这些东西。确保你在其他任何事情之前都调用了physics.start()。