Adding the score on bounce collision

Hi guys,

I’ve got one more question. In my game, the user will get a point every time the ball hits the ground. The ball is controlled by the player. The ball has some bounce to it.

Now the problem is that for some reason the ball always detects to many collisions. So for example, if it hits the ground once, the score goes up by 3. I tried removing the eventlistener every time when the ball hits the ground and re-adding the listener after 100 milliseconds. But this is giving some real strange behaviour (Scores going up with what seems random values when a collision occurs).

This is the code:

 function functions.startCollisionDetector() ball:addEventListener("collision", functions.collisionDetector) end function functions.collisionDetector(event) if event.other == floor then score = score + 1 scoreTxt.text = "score: " .. score ball:removeEventListener("collision", functions.startCollisionDetector) timers.restartCollisionDetector = timer.performWithDelay(100, functions.startCollisionDetector, 1) end end

Could someone help me? :slight_smile:

Kind regards

The also has some major stutters, I think it is because of this piece of code :frowning:

Events have phases such as “began” and “ended”, if you aren’t checking for the phase then the code will run each time one is triggered.  See this documentation

change your function to this :

 function functions.collisionDetector(event) if event.phase == "began" then if event.other == floor then score = score + 1 scoreTxt.text = "score: " .. score end end end

Also, you don’t need to remove and add the event listener each time the collision happens.

good luck :slight_smile:

The also has some major stutters, I think it is because of this piece of code :frowning:

Events have phases such as “began” and “ended”, if you aren’t checking for the phase then the code will run each time one is triggered.  See this documentation

change your function to this :

 function functions.collisionDetector(event) if event.phase == "began" then if event.other == floor then score = score + 1 scoreTxt.text = "score: " .. score end end end

Also, you don’t need to remove and add the event listener each time the collision happens.

good luck :slight_smile: