enterFrame listener won't stop

Hi!

I’m programming a game in which I want to evaluate some condition (the velocity of a ball) every frame, just to make sure it has stopped. When it stops, it must change the scene.

I can’t make it to stop the listener, unless I do it in the unload function. But then it’s too late. Can I remove a listener from the same function?

It’s 7 o’clock, and my brain can explain himself better than this. I’m posting my code so you all understand what I mean:

 local gameLoop = function()  
  
 local vx  
 local vy  
  
 vx, vy = pilota:getLinearVelocity()  
  
 if (math.abs(vx) \< 20) and (math.abs(vy) \< 20) then  
  
 pilota:setLinearVelocity(0, 0)  
 Runtime:removeEventListener("enterframe", gameLoop)  
  
 \_G.posX = pilota.x  
 \_G.posY = pilota.y  
  
 if (contadorGolpes == #arrayColores) then  
  
 gameOver("yes")  
  
 else  
  
 print("Fracàs!")  
 gameOver("no")  
  
 end  
 end  
  
 end  

Is this ok? Because this listener won’t stop listening.

Thanks in advance!
Hector [import]uid: 36639 topic_id: 9683 reply_id: 309683[/import]

I had the exact same problem - I just couldn’t remove that event listener. I tried storing the reference in global variables, in different function, etc. I ended up being able to remove it in the actual handler function itself like this, by using “self”:

[lua]function moveDamageText (self, event)

– code to move the damageText to track the enemy each frame

– if statement here to test for when I want to destroy it
Runtime:removeEventListener (“enterFrame”, self )

end
function damageEnemy (enemy)

– code to create the damageText

damageText.enterFrame = moveDamageText
Runtime:addEventListener ( “enterFrame”, damageText )

end[/lua]

But that’s the only thing that worked. I would love to know why it wouldn’t get in any other function. [import]uid: 49372 topic_id: 9683 reply_id: 35283[/import]

Try changing the definition of your function to this:

local function gameLoop()  

The reason is that in your first version the variable “gameLoop” is only defined after the function has finished, meaning when you try to remove the listener the variable is still nil. [import]uid: 5833 topic_id: 9683 reply_id: 35285[/import]

Graham is correct - an alternative is to first declare the local variable gameLoop:

[lua]local gameLoop

gameLoop = function()

end[/lua]
-FrankS.
[import]uid: 8093 topic_id: 9683 reply_id: 35289[/import]

Oh. And here I thought he did not capitalize “enterFrame” properly.

Runtime:removeEventListener("enterframe", gameLoop)  

should be

Runtime:removeEventListener("enterFrame", gameLoop)  

But what would I know…

C. [import]uid: 24 topic_id: 9683 reply_id: 35294[/import]

Thanks, all of you! [import]uid: 36639 topic_id: 9683 reply_id: 35350[/import]