I have been watching the latest Corona Hangouts on YouTube and have been learning a lot. For my new app I wanted to make things more object-oriented. So I used a separate “class” file for the player, enemy and joystick. However, I am having trouble trying to create a collision event with the player and enemy.
I read that when you add physics to an object, you can’t move it the same way you move a regular display object (e.g. player.x = player.x + 1), because the physics body will stay in place. Does this mean I would require a weld joint? Then how would I move it? With a linear impulse or force?
Anyhow, this is what I had in my player class. I will show the parts where it reacts to a joystick movement (which is currently working) and then I attempt to set up a collision listener:
player.lua:
local Player = {} function Player.new() local playerGroup = display.newGroup() local player = display.newCircle(playerGroup, 0, 0, display.contentWidth\*0.02) — For easy reference playerGroup.obj = player -- Movement handler, for the "direction" custom event function playerGroup:direction(event) -- Multi-direction controller local angle = event.angle local dX = Cos( Rad(angle-360) ) if (dX \< 0 and self.x \> self.minX) or (dX \> 0 and self.x \< self.maxX) then self.x = self.x + dX end local dY = -Sin( Rad(angle-360) ) if (dY \< 0 and self.y \> self.minY) or (dY \> 0 and self.y \< self.maxY) then self.y = self.y + dY end return true end function playerGroup:kill() Runtime:removeEventListener("direction", self) end -- Collision detection function playerGroup:collision(self, event) print("collision: ", event.phase) if event.phase == "began" then print("ouch!") end end playerGroup:addEventListener("collision”) -- Listen for custom event 'direction' from joystick Runtime:addEventListener("direction", playerGroup) return playerGroup end return Player
Then in my main code I create the player and enemy:
local plib = require("player") player = plib.new() group:insert(player) physics.addBody(player, "kinematic", {isSensor = false}) local elib = require("enemy") enemy[id] = elib.new() group:insert(enemy[id]) physics.addBody(enemy[id], "kinematic", {isSensor = false})
So this example above does not work, because I don’t see any event generated when my player runs into the enemy.
What am I doing wrong here?