【问题标题】:Corona SDK - Handling Touch Events in LuaCorona SDK - 在 Lua 中处理触摸事件
【发布时间】:2013-05-23 23:36:48
【问题描述】:

我正在 Lua 中开发一个简单的应用程序,以便更好地感受 Corona SDK:一个红球在屏幕上弹跳并在用户触摸它时切换方向。但是,每当我在 Corona Simulator 中单击球时,都会多次调用触摸事件。这是我的代码:

local xdirection,ydirection = 1,1
local xpos,ypos = display.contentWidth*0.5,display.contentHeight*0.5
local circle = display.newCircle( xpos, ypos, 20 );
circle:setFillColor(255,0,0,255);

local x_speed = 5
local y_speed = 5 

local function animate(event)
    xpos = xpos + ( x_speed * xdirection );
    ypos = ypos + ( y_speed * ydirection );

    if (xpos > display.contentWidth - 20 or xpos < 20) then
            xdirection = xdirection * -1;
    end
    if (ypos > display.contentHeight - 20 or ypos < 20) then
            ydirection = ydirection * -1;
    end

    circle:translate( xpos - circle.x, ypos - circle.y)
end

local function switch(event)
    xdirection = xdirection * -1;
    ydirection = ydirection * -1;
    print "Switched!"
end

Runtime:addEventListener( "enterFrame", animate );
circle:addEventListener("touch",switch);

每次我在模拟器中点击球时,“切换!”多次打印。有什么想法吗?

【问题讨论】:

    标签: lua touch coronasdk


    【解决方案1】:

    当你使用 on touch 事件时会有三个事件阶段触发

    began, moved, ended
    

    如果您想在触摸事件中触发一个阶段,请将其放在您的代码中

    local function switch(event)
        if (event.phase == "ended") then
        xdirection = xdirection * -1;
        ydirection = ydirection * -1;
        print "Switched!"
        end
    end
    

    【讨论】:

      【解决方案2】:

      “触摸”事件在触摸事件的开始和结束时被调用两次。尝试在您的 switch 函数中打印 event.phase。

      你应该使用:

      circle:addEventListener("tap",switch);
      

      【讨论】:

        猜你喜欢
        • 2013-04-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-22
        • 2014-01-17
        • 1970-01-01
        相关资源
        最近更新 更多