Multiple spawned objects on collision - Corona SDK
Please help! I'开发者_开发百科m trying to spawn 5 balls one by one from the sky and have them disappear as soon as they hit the ground or when they hit another user-controlled object that's on the ground. The good thing is that I can spawn the balls successfully as intended, but when they hit the ground (or the other user-controlled object on the ground), they don't disappear. I've been going through a ton of sample code since the past 2 days but I can't figure out how to do it. The game does run, but the debug terminal gives me an error saying: runtime error - attempt to index global 'self' . Here's the source code:
local randomBall = function()
ball = display.newImage( "hardball.png" )
ball.x = math.random (30, 450); ball.y = -20
physics.addBody( ball, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )
local function whenHit (event)
if(event.phase == "began") then
self:removeSelf()
end
end
ball:addEventListener("collision", whenHit)
end
timer.performWithDelay( 500, randomBall, 5 )
Telling us what line that error was on would have been nice, but I can see your problem is in the function whenHit()
It refers to a variable 'self' only you never define that variable. Presumably you want that function to act as a method of 'ball' so the function declaration should use the colon syntax and look something like ball:collision(event)
Note that Corona has two ways of setting event listeners. It's explained here in their documentation: http://developer.anscamobile.com/content/events-and-listeners
And then this page in their documentation explains how that applies to collision events: http://developer.anscamobile.com/content/game-edition-collision-detection
It looks like what you are trying to do is a table listener on the ball, in which case your call to addEventListener should be ball:addEventListener("collision", ball) and then the function is ball:collision(event)
The other method they describe is a global listener function and then use event.object1 inside the function to refer to the object that collided.
How to spawn objects the right way: https://coronalabs.com/blog/2011/09/14/how-to-spawn-objects-the-right-way/
精彩评论