quick-cocos2d-x遊戲開發【7】——scheduler 定時器

定時器用的地方還是比較多的,遊戲中的邏輯判斷很多都是採用每幀執行。quick對於schedule的封裝在scheduler這個lua文件中。如果是第一次接觸quick的話,可能按照官方的api來寫一個定時器被報錯,提示schedule是一個nil值,這是因爲其他的模塊在初始化時都是被加載的,唯獨這個scheduler沒有載入,所以在使用的時候,第一件事是引入這個模塊,

local scheduler = require("framework.scheduler")

剩下的就可以看着api來寫了,在寫quick的定時器之前還是再複習一下cocos2dx原生lua對於定時器的寫法。

每幀調用的,

void scheduleUpdateWithPriority (int priority)

void scheduleUpdateWithPriorityLua (int nHandler,int priority)


指定調用間隔時間的,

unsigned int scheduleScriptFunc (unsigned int nHandler, float fInterval, bool bPaused)


還有取消定時器事件

void unscheduleScriptEntry (unsigned int uScheduleScriptEntryID)


quick的scheduler主要是對後面兩個函數的封裝。在c++的cocos使用中,我們使用定時器,無非就是每幀調用,間隔時間調用無數次,間隔時間調用指定次數,間隔時間調用一次,取消調用這幾個。

我們依次來看下,

每幀調用,

    local time = 0
    local function update(dt)
        time = time + 1
        label:setString(string.format("%d", time))
    end

    scheduler.scheduleUpdateGlobal(update)

間隔一定時間調用,

    local time = 0
    local function onInterval(dt)
        time = time + 1
        label:setString(string.format("%d", time))
    end

    scheduler.scheduleGlobal(onInterval, 1)


間隔時間調用一次,這個封裝的不錯,很常用

    local time = 0
    local function onInterval(dt)
        time = time + 1
        label:setString(string.format("%d", time))
        print("over")
    end

    scheduler.performWithDelayGlobal(onInterval, 1)

可以看下這個是怎麼實現的,

function scheduler.performWithDelayGlobal(listener, time)
    local handle
    handle = sharedScheduler:scheduleScriptFunc(function()
        scheduler.unscheduleGlobal(handle)
        listener()
    end, time, false)
    return handle
end

其實就是在間隔一定時間後,將其停止,然後執行一次回調函數就可以了。


封裝的最後一個是停止這些定時器,

scheduler.unscheduleGlobal()

它的參數是前面那些定時器返回的句柄,所以如果需要在後面停止掉,記得在創建的留一個返回值就好了。


不過在遊戲中,我們可能會做一個倒計時,也就是間隔一定時間調用指定的次數,這個是在quick中沒有封裝的,但是我們還是可以自己動手實現一下,原理也很簡單,每次執行一次就計個數,達到指定的次數就停止定時器,

    local handle
    local interval = 1
    local repeatIndex = 3
    local index = 0
    local sharedScheduler = CCDirector:sharedDirector():getScheduler()
    handle = sharedScheduler:scheduleScriptFunc(function()
        index = index + 1
        label:setString(string.format("%d", index))
        if index >= repeatIndex then
            scheduler.unscheduleGlobal(handle)
            print("over")
        end
    end, interval, false)


效果如圖



這樣就ok了,大家可以自己試一試哈。

定時器就是這樣子了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章