2

I have some code here that when an image (which is my button) is clicked, a new image randomly appears. This is due to a table I created with some images inside.

local animalPic

local button = display.newImageRect ("images/animalBtn.jpg", 200, 200)
button.x = 250
button.y = 50

local myPics = {"images/animal1.png", "images/animal2.png"}

function button:tap (event)


    local idx = math.random(#myPics) 
    local img = myPics[idx] 
    local animalPic = display.newImage(img)
    animalPic.x = contentCenterX
    animalPic.y = contentCenterY
end

button:addEventListener ("tap", button)

The problem with it is the graphics just keep piling up when I click the button. The correct behavior should be -

Button is clicked and an image is shown while removing the previous image. How do I incorporate this behavior? I already tried the removeSelf command and it doesnt work......Any help appreciated.

2 Answers 2

1

You declare animalPic each time you enter function. You should declare it once and then remove it and replace it by another. It should be:

local animalPic

function button:tap (event)
    local idx = math.random(#myPics) 
    local img = myPics[idx] 
    animalPic:removeSelf()
    animalPic = nil
    animalPic = display.newImage(img)
    animalPic.x = contentCenterX
    animalPic.y = contentCenterY
end
0

When you call display.newImage(), you are adding a new image. The problem is that you need to remove/hide the original one. Perhaps you really need two objects - one for the current image and one for the tap event. When the tap event occurs, hide the old image and display the new one. An alternative would be to load all the images in their own imageRects and then toggle them on and off.

1
  • I'm not clear on what you mean? Can you provide code sample? I'm still consider myself a beginner.....Thanks. :D
    – Joe C.
    Apr 22, 2014 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.