He Lin
He Lin

Reputation: 1

Objects not responding to tap event for lua

I'm building a simple game, where player clicks a ball that moves randomly to get scores. However, when I'm testing my game, I realized the tap function is not working properly. When I'm trying to click on the moving ball, sometimes the score will increase, but sometime there is no response. Here is the codes that I used. Thanks for the help!

    local ball = display.newImage( "ball.png" )
        ball.x = math.random(0,w)
        ball.y = math.random(0,h)
        physics.addBody( ball)


    function moveRandomly()
    ball:setLinearVelocity(math.random(-50,50), math.random(-50,50));
    end
    timer.performWithDelay(500, moveRandomly, 0);

    ball.rotation = 180
    local reverse = 1

    local function rotateball()
        if ( reverse == 0 ) then
            reverse = 1
            transition.to( ball, { rotation=math.random(0,360), time=500,             transition=easing.inOutCubic } )
        else
            reverse = 0
            transition.to( ball, { rotation=math.random(0,360), time=500,         transition=easing.inOutCubic } )
        end
    end

    timer.performWithDelay( 500, rotateball, 0 )

    local myText, changeText, score

    score = 0


    function changeText( event )
        score = score + 1
        print( score.."taps")
        myText.text = "Score:" ..score
        return true
    end

    myText = display.newText( "Score: 0", w, 20, Arial, 15)
        myText:setFillColor( 0, 1, 1)

    myText:addEventListener( "tap", changeText)
    ball:addEventListener("tap", changeText)

Upvotes: 0

Views: 128

Answers (1)

brando
brando

Reputation: 313

Your code looks fine, especially since you say that it works sometimes.

The only thing I can think is that maybe you should use the "touch" event instead of the "tap" event, since the tap won't trigger until you take your finger off the screen. See https://docs.coronalabs.com/guide/events/touchMultitouch/index.html

ball:addEventListener("touch", changeText)

You'll want to use the "began" phase of the event so it only increases the score once per touch (when it starts).

function changeText( event )
    if ( event.phase == "began" ) then
        score = score + 1
        print( score.."taps")
        myText.text = "Score:" ..score
    end
    return true
end

Upvotes: 1

Related Questions