user3059109
user3059109

Reputation: 45

Corona sdk having trouble stopping timers on individual spawned objects

I have a beat em up game and a 'punch' sound is played on a timer if an enemy collides with my character as shown below:

local function hitSound()
local hsound = math.random(#sfx.hit)
audio.play(sfx.hit[hsound])
end

--------------------------------------------------CHARACTER COLLISION---------------

local function guyCollision(self, event)
if event.other.type == "enemy1"then

if event.phase == "began" then
hitTimer = timer.performWithDelay(500,hitSound,0)
event.other:setSequence("punch")
event.other:play()
end

if event.phase == "ended" then
timer.pause(hitTimer)
end

This works fine when my character is taking down just one enemy at a time but if there are more than one spawned enemy (which there usually is) fighting my character when i kill them the punching sound remains. Also when i call audio.fadeout() when my character dies the punch sounds don't fade out with the other sounds/music :s

Someone suggested to me to assign the timer to the specific enemy in question using its index in its table but im unsure of how to do this... is this the best way? I just don't know how to get that enemys current index.. any help much appreciated!

Heres my enemy spawn code:

local spawnTable2 = {}


local function spawnEnemy()
enemy1 = display.newSprite( group, sheetE, sequenceData2 )
enemy1.x=math.random(100,1300)
enemy1.y=math.random(360,760)
enemy1.gravityScale = 0
enemy1:play()
enemy1.type="coin"
enemy1.objTable = spawnTable2
enemy1.index = #enemy1.objTable + 1
enemy1.myName = "enemy" .. enemy1.index
physics.addBody( enemy1, "kinematic",{ density = 1.0, friction = 0.3, bounce = 0.2 })
enemy1.isFixedRotation = true
enemy1.type = "enemy1"
enemy1.enterFrame = moveEnemy
Runtime:addEventListener("enterFrame",enemy1)
enemy1.objTable[enemy1.index] = enemy1
return enemy1
end

Upvotes: 0

Views: 448

Answers (1)

Rob Miracle
Rob Miracle

Reputation: 3063

I think your problem is that your hitTimer variable is probably being overwritten and you can only cancel the last one. You could probably do: self.hitTimer to get around it.

Rob

Upvotes: 1

Related Questions