Event Listener is spawning a lot of objects! Help!

I've created an Event Listener to spawn a ball when the screen is touched.
However, when ever I "touch" (click) the screen on the simulator, many balls are spawned. A new ball is spawned every time you move the mouse, and two times when you click. It's honestly quite bizarre.

1
2
3
4
5
6
7
8
function spawnBall()
ball = display.newImage("ball.png")
ball.x = 180
ball.y = 80
physics.addBody( ball, { density=2.0, friction=0.5, bounce=0.3 } )
end
 
Runtime:addEventListener( "touch", spawnBall )

Try this (haven't tried it myself so not sure if it works):

1
2
3
4
5
6
7
8
9
10
function spawnBall(event)
    if event.phase == "began" then
        ball = display.newImage("ball.png")
        ball.x = 180
        ball.y = 80
        physics.addBody( ball, { density=2.0, friction=0.5, bounce=0.3 } )
    end
end
 
Runtime:addEventListener( "touch", spawnBall ) 

@ codepunk_schmidt is right. the touch event listener is triggered many times for a single touch. but the began phase is triggered only once.

alternatively you can try using "tap" event.

1
2
3
4
5
6
7
8
function spawnBall()
ball = display.newImage("ball.png")
ball.x = 180
ball.y = 80
physics.addBody( ball, { density=2.0, friction=0.5, bounce=0.3 } )
end
 
Runtime:addEventListener( "tap", spawnBall )
views:1426 update:2011/10/11 15:24:38
corona forums © 2003-2011