本帖基於quick cocos2dx2.2.6版本。
序列幀動畫:顧名思義就是在一定的時間內播放多張圖片。
基本原理非常簡單,在一個固定的位置1秒時間內輪詢播放有限數量的不同圖片。比如1秒中播放24張圖(FPS=24)
在quick引擎中可以通過framwork中的transition.lua文件中得transition.playAnimationForever(target, animation, delay)接口來實現動畫的播放,其源碼如下:

function transition.playAnimationForever(target, animation, delay) local animate = CCAnimate:create(animation) local action if type(delay) == "number" and delay > 0 then target:setVisible(false) local sequence = transition.sequence({ CCDelayTime:create(delay), CCShow:create(), animate, }) action = CCRepeatForever:create(sequence) else action = CCRepeatForever:create(animate) end target:runAction(action) return action end
在需要顯示動畫的界面里加入如下代碼:
local node = display.newSprite() :pos(display.cx,display.cy) :addTo(self) transition.playAnimationForever(node, GameResouce.createEffect("filename","ui"), 1)
注意這里的node一定要是一個sprite實例。
GameResouce是對動畫資源的一個簡單封裝類型,大概實現寫資源緩沖及創建動畫的功能。功能代碼如下:
GemeResource = GemeResource or {} local sharedSpriteFrameCache = CCSpriteFrameCache:sharedSpriteFrameCache()
--創建緩存 function GemeResource.createCacha() assert(GemeResource.cacha == nil) GemeResource.cacha = {} end --清理緩存 function GemeResource.releaseCacha() assert(GemeResource.cacha) for k,v in pairs(GemeResource.cacha) do sharedSpriteFrameCache:removeSpriteFramesFromFile(k..".plist") CCTextureCache:sharedTextureCache():removeTextureForKey(k..".png") end GameResource.cacha = nil end function GameResource.createEffect(name, dir, zoom) zoom = zoom or 1 -- 加載plist local path = "anim/" .. dir .. "/" .. name--默認將動畫資源放入res/anim目錄下 sharedSpriteFrameCache:addSpriteFramesWithFile(path..".plist", path..".png") if GameResource.cacha then GameResource.cacha[path] = true end local frame_name = string.split(name, "_")[1]--plist中圖片的名稱命名規則為xxx_001.png,所以此處將圖片名稱中得xxx字符串取出 local frames = {} local count = 1 local name = "" while true do local frame = GameResource.loadFrame(frame_name, count) if not frame then break end table.insert(frames, frame) count = count + 1 end if #(frames) <= 0 then echoError("error ", dir.." name:"..name) return nil end local fps = 1/24 --設置默認fps為24 local animation = display.newAnimation(frames, fps)--創建動畫實例 animation:setDelayPerUnit(animation:getDelayPerUnit()*zoom)--zoom的作用:可以在不改變fps的情況下加速或放慢動畫的播放頻率 return animation end
function GameRes.loadFrame(_name, _id) return sharedSpriteFrameCache:spriteFrameByName(string.format("%s_%03d.png",_name,_id)) end
return GemeResource
完整的測試代碼如下:
local AnimationTest = class("AnimationTest",function() return display.newScene("AnimationTest") end) function AnimationTest:ctor() GameResource.createCacha() local node = display.newSprite() :pos(display.cx,display.cy) :addTo(self) transition.playAnimationForever(node, GameResource.createEffect("ani","ui"), 0)--ui為res下的目錄 ani為動畫文件的名稱(ani.plist,ani.png 兩個文件通過TP工具導出) end function AnimationTest:onEnter() end return AnimatiionTest