How do I test for collisions in main.lua in corona sdk when the objects to test for are defined in another class? I have an image in player class, and an image in enemy class. In main how do I detect if these images collide?
local function onGlobalCollision (event)
if ( event.phase == "began" ) then
print( "began: " .. event.object1.myName .. " & " .. event.object2.myName )
end
end
Runtime:addEventListener( "collision", onGlobalCollision )
It really comes down to how you've setup your classes. You might need to post more of your code. I've created this example which works as expected:
box.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
main.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 )
I'm pretty sure you could even remove the stuff from main altogether. Make sure you have called physics.start() before anything else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.