Collision Through Functions

Hi all,

I’ve been trying to get my game to work with collision detection and have came across a problem. I have a function that spawns a player to the screen. This function needs to be called a few times and the player respawns throughout the game.

 local spawnPlayer = function()  
 gameIsActive = true  
 local gameChar = gameSettings["gameChar"]  
 if gameChar == "player1" then  
 playerObject = display.newImage("player1.png")  
 end   
  
 physics.addBody( playerObject, "kinematic", { density = 0, friction = 0, bounce = 0, } )  
  
 playerObject.x = 0  
 playerObject.y = 160  
 playerObject.name = "player"  
  
 gameGroup:insert(playerObject)  
 end  

I want to add the following 2 lines outside the function (obviously) but it says playerObject returns a nil value (which I’m guessing is because the playerObject is only in the scope of the function).

playerObject.collision = onCollision  
playerObject:addEventListener("collision", player)  

Does anyone know a way to overcome this problem?

Thanks in advance,
Louis [import]uid: 65150 topic_id: 11723 reply_id: 311723[/import]

You could use a Runtime eventListener instead. You have already assigned a name to the playerObject so you can use that to determine a collision. [import]uid: 27965 topic_id: 11723 reply_id: 42657[/import]

add the collision detectors inside your spawnPlayer function right below gameGroup:insert(playerObject). That way it will only be calling those detectors when a player is actually spawned. [import]uid: 69700 topic_id: 11723 reply_id: 42671[/import]