I’m making an app where I spawn coins and add horizontal gravity to them. I was having problems with my previous code that, whenever the coins collided, whether with the player or the enemy, it added a point to the score. I tried to fix it, but now that coins just bounce when they hit the player (or the enemy)
How can I make that the coins disappear (and add 1 point) only if they hit the player?
[code]
local player
local enemy
–Function to spawn a coin
local function spawn(params)
local coin = display.newImage(params.image)
setPos(coin, W + 10, math.random(10, H - 10))
–Set the coin table to a table passed in by parameters
coin.objTable = params.objTable
–Automatically set the table index to be inserted into the next available table index
coin.index = #coin.objTable + 1
–Give the coin a custom name
coin.myName = "coin : " … coin.index
–If the coin should have a body create it, else dont.
if params.hasBody then
–Allow physics parameters to be passed by parameters:
coin.density = params.density or 0
coin.friction = params.friction or 0
coin.bounce = params.bounce or 0
coin.isSensor = params.isSensor or false
coin.bodyType = params.bodyType or “dynamic”
physics.addBody(coin, coin.bodyType, {density = coin.density, friction = coin.friction, bounce = coin.bounce, isSensor = coin.isSensor})
end
–The coins group
coin.group = params.group or nil
–If the function call has a parameter named group then insert it into the specified group
coin.group:insert(coin)
–Insert the coin into the table at the specified index
coin.objTable[coin.index] = coin
function onCollision(e)
local function updateScore()
textScore.text = "Score: " … score
end
local function addScore()
score = score + 1
end
if e.phase == “began” then
if e.other.myName == ‘player’ then
coin:removeSelf()
coin = nil
addScore()
updateScore()
end
end
end
coin:addEventListener(“collision”, onCollision)
return coin
end
local localGroup = display.newGroup()
local spawnTable = {}
function spawnCoin()
local spawns = spawn(
{
image = “src/coin.png”,
objTable = spawnTable,
hasBody = true,
bodyType = “dynamic”,
group = localGroup,
}
)
end
coinTimer = timer.performWithDelay(1000, spawnCoin, 0)
[/code] [import]uid: 154404 topic_id: 32634 reply_id: 332634[/import]
[import]uid: 52491 topic_id: 32634 reply_id: 129961[/import]