Hello,
I used this exact code/method for another one of my projects and it worked perfectly fine. But in this new project, I’m trying to implement a lock and key and it won’t work. Basically, the player collides with the key, key disappears and if player collides with the lock while playerHasKey = true, the lock disappears.
However, when the player collides with the key it does nothing. It won’t even print in the console.
Here’s the code:
local myPlayer = display.newImageRect("/images/HUD/player1.png", 50, 50)
myPlayer.x = display.contentCenterX - 150
myPlayer.y = display.contentCenterY - 100
playerHasKey = false
physics.addBody( myPlayer, “dynamic”, {density = 1.0, radius = 25, friction = 0.7, bounce = 0.3})
myPlayer.name = “myPlayer”
local keyBlue = display.newImageRect("/images/Items/keyBlue.png", 75, 65)
keyBlue.x = display.contentCenterX - 100
keyBlue.y = display.contentCenterY
keyBlue.objType = “key”
keyBlue.myName = “keyBlue”
physics.addBody(keyBlue, “dynamic”)
local lockBlue = display.newImageRect("/images/Tiles/lock_blue.png", 65, 75)
lockBlue.anchorX = 0.0
lockBlue.x = display.contentCenterX + 100
lockBlue.y = display.contentCenterY
lockBlue.objType = “lock”
lockBlue.myName = “lockBlue”
physics.addBody(lockBlue, “dynamic”, {density = 1.0, friction = 0.8, bounce = 0.3})
function grabKey(event)
if(event.object1.myName == “myPlayer” and event.object2.myName == “keyBlue”) then
print(“Player has grabbed the key!”)
playerHasKey = true
event.object2:removeSelf()
end
end
Runtime:addEventListener( “collision”, grabKey)
function playerWins(event)
if(event.object1.myName == “myPlayer” and event.object2.myName ==“lockBlue”) then
if (playerHasKey == true ) then
event.object2:removeSelf()
end
end
end
Runtime:addEventListener(“collision”, playerWins)
myPlayer has another event listener for touch which enables drag and drop. I thought that might be conflicting, but I commented it out and the problem is still there. Not sure what else it could be. I’m using the same exact code from another project.