A little help with this code?

Hey all,

I’m working on learning LUA, so I’m messing around with creating a Balloon Pop style game.

Here’s the full code… It’s not too long.

[lua]local physics = require(“physics”)
physics.start()

local height = display.contentHeight
local balloonOnScreen = 0
local sky = display.newImage(“sky.jpg”)
local ground = display.newImage(“ground.png”)
local balloon

ground.x = display.contentWidth / 2
ground.y = 30

physics.addBody(ground, {friction=0.5})
physics.setGravity(0,-9.8)
ground.bodyType = “static”

function createBalloon(null)
balloon = display.newImage(“balloon.png”)
balloon.rotation = 5
balloon.x = math.random(0,display.contentWidth)
balloon.y = display.contentHeight + 100
physics.addBody(balloon, {density=2.0, friction=0.5, bounce=0.3})

balloonOnScreen = 1
end

function moveStuff(null)
transition.to(textObject, {time=500, y=textObject.x+1000})
end


–This is where I get a runtime error

function balloon:tap(event)
print(“tap”)
balloonOnScreen = 0
balloon:removeSelf()
end

timer.performWithDelay(500, createBalloon, 50)
balloon:addEventListener(“tap”,balloon)[/lua]

The code works great when the balloon:tap function is commented out, but I need a balloon to unload itself when it’s tapped.

How can I do this with my current setup? [import]uid: 78380 topic_id: 12854 reply_id: 312854[/import]

you are creating multiple balloons and the last one created is referred to by the variable balloon, so if you tap the last one, it will disappear.

To enable what you are after, create the balloons, but retain a handle to them in an array to be able to remove them

or place the functions inside of the createBalloon function so that they are local to that created object.

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 12854 reply_id: 47173[/import]

Try something like this
[lua]local function tapBalloon(event)
if event.phase == “ended” then
event.target:removeSelf()
end
end

function createBalloon(null)
local balloon = display.newImage(“balloon.png”)
balloon.rotation = 5
balloon.x = math.random(0,200)
balloon.y = 400
physics.addBody(balloon, {density=2.0, friction=0.1, bounce=0.3})

–added the event inside the createBalloon Function
balloon:addEventListener(“touch”,tapBalloon)
end

timer.performWithDelay(500, createBalloon, 50)[/lua] [import]uid: 71210 topic_id: 12854 reply_id: 47237[/import]

Thanks Technowand - excellent example.

It works perfectly. [import]uid: 78380 topic_id: 12854 reply_id: 47240[/import]