2015-12-15 61 views
0

我正在構建一個簡單的遊戲,玩家點擊一個隨機移動以獲得分數的球。但是,當我測試我的遊戲時,我意識到輕擊功能無法正常工作。當我試圖點擊移動的球時,有時分數會增加,但有時候沒有反應。這是我使用的代碼。謝謝您的幫助!對於lua沒有響應的點擊事件

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) 

回答

1

你的代碼看起來很好,特別是因爲你說它有時可以工作。

我唯一能想到的是,也許你應該使用「觸摸」事件而不是「點擊」事件,因爲直到你將手指從屏幕上移開,觸摸纔會觸發。見 https://docs.coronalabs.com/guide/events/touchMultitouch/index.html

ball:addEventListener("touch", changeText) 

你要使用事件的「開始」階段,因此只有每個觸摸增加一度將比分(在啓動時)。

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