luacoronasdkcorona-storyboard

Tap/Touch function on adding/removing images on corona sdk


I am trying to make a game, similar to Simon Says. I am currently using the corona sdk, and I would be very grateful if you were to help me with this! I have already defined my box1 variable with an image. I am trying to make it so when I click the image of the box, another box of different color shows up on top of it. I would like it so the box that appears disappears when I let go of my mouse. Below is part of my code:

local function lightbox(event)
if event.phase == "began" then
    local clickedbox1 = display.newImage("clickedbox.png")
    clickedbox1.x = display.contentWidth/5
    clickedbox1.y = display.contentWidth/2
end
if event.phase == "ended" then
    clickedbox1: removeself()
    clickedbox1 = nil
end
end

-->Add the listener to our boxes
box1:addEventListener("touch", lightbox)

Thanks for your time!


Solution

  • You can use event.target.x inside of your touch function so that the popupbox will be displayed on top of the touched image.

    NOTE: Change the image assets given to your image assets

    local popupImage
    
    local onTouchListener = function(event)
    
        if (event.phase == "began" ) then
    
            popupImage = display.newImageRect("images/btn_cancel_reset.png", 55,18)
            popupImage.x = event.target.x
            popupImage.y = event.target.y
    
    
        elseif(event.phase == "ended" or event.phase == "moved") then
            --ADD EVENT.PHASE == "MOVED" SINCE THE IMAGE WILL NOT BE REMOVED 
            --WHEN YOU TOUCH AND DRAG YOUR MOUSE. YOU CAN REMOVE IT IF YOU WANT
    
            if (popupImage ~= nil) then
    
                popupImage:removeSelf()
                popupImage = nil
    
            end
        end
    
    
    end
    
    
    local btnclick = display.newImageRect("images/btn_buy_more_error.png", 126,18)
    btnclick.x = display.contentWidth/2
    btnclick.y = display.contentHeight/2
    btnclick:addEventListener( "touch", onTouchListener)