Cocos仿unity按钮机制

去年做androidtv游戏时写的,记录在别的博客网站,一并拿过来。虽然现在已经投入unity的怀抱,加上看了廖大大和触控的工资纠纷。

--根据不同的平台绑定按键
if cc.Application:getInstance():getTargetPlatform() == 2 then
    GSKeyCode = {
        left = 26,
        right = 27,
        top = 28,
        bot = 29,
        ok = 35
        }
else
    GSKeyCode = {
        left = 159,
        right = 160,
        top = 161,
        bot = 162,
        ok = 163,
        menu = 18
        }
end

--初始化 监听系统的按键消息
function GSKeypadTool:start()
    local listener = cc.EventListenerKeyboard:create()
        listener:registerScriptHandler(handler(self,self.onKeyReleased),cc.Handler.EVENT_KEYBOARD_RELEASED)
        listener:registerScriptHandler(handler(self,self.onKeyPressed),cc.Handler.EVENT_KEYBOARD_PRESSED)

        cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(listener,1)

        cc.Director:getInstance():getScheduler():scheduleScriptFunc(handler(self,self.update),0,false)

        --保存按键的数据
        self.mKeyReleased = {}
        self.mKeyPressed = {}
    end

    --按键按上清空该按键的数据
    function GSKeypadTool:onKeyReleased(keyCode,event)
        --cc.KeyCode.Key_BACK
        --[[
            清空按下时间
        ]]
        self.mKeyPressed[keyCode] = nil
        --[[
            创建按上时间
        ]]
        --此处保存为false 然后再update改为true,update后的一帧改为false 确保这个事件只存活1帧
        self.mKeyReleased[keyCode] = false
    end

    --按键按下
    function GSKeypadTool:onKeyPressed(keyCode,event)
        --保存按键按下时的数据
        local pressedData = {}
        pressedData.frame = 0
        --每20帧处理一次点击效果,相当于长按
        pressedData.nextEffectFrame = 20
        pressedData.effectTimes = 0
        self.mKeyPressed[keyCode] = pressedData
    end


function GSKeypadTool:update(dt)

    for keyCode,keyData in pairs(self.mKeyReleased) do
        if keyData == false then
            self.mKeyReleased[keyCode] = true
         end
    end

    for keyCode,keyData in pairs(self.mKeyPressed) do
        keyData.frame = keyData.frame + 1

        if  keyData.frame > keyData.nextEffectFrame then

            keyData.effectTimes = keyData.effectTimes + 1
            --长按加速
            keyData.nextEffectFrame = math.max(keyData.nextEffectFrame - keyData.effectTimes * 6 , 5) + keyData.nextEffectFrame
        end
    end
end


function GSKeypadTool:getKeyUp(keyCode)
    return self.mKeyReleased[keyCode] 
end

function GSKeypadTool:getKeyDownTime(keyCode)
    if self.mKeyPressed[keyCode] then
        return self.mKeyPressed[keyCode].frame
    end
    return nil
end

GSKeypadTool:start()

你可能感兴趣的:(lua)