quick-lua 獲取Cocos Studios動畫播放回調
阿新 • • 發佈:2019-01-04
quick-lua 版本是3.5
cocos studios是2.0以上,目前是最新版本
在cocos studios中回撥使用幀事件也是可以的,就是在關鍵幀上設定回撥事件:
設定的時候,要選中開始記錄動畫,然後選中關鍵幀,再設定事件名稱。在動畫執行到這一幀時會觸發該事件,在lua中使用方式為:
但這種方式很繁瑣,在修改動畫的時候很容易忘記有這個事件而出錯local eventFrameCall = function(frame) local eventName = frame:getEvent() if eventName == "wait" then end end end timeline:clearFrameEventCallFunc() timeline:setFrameEventCallFunc(eventFrameCall) timeline:play("wait", false)
在使用cocosbuilder的時候,可以設定動畫回撥函式。在cocos studios也有這個的回撥,但在quick-lua 3.5中還沒有支援。所以下面記錄另外一種回撥方式。
簡單說就是獲取動畫執行時間,手動設定回撥方法:
timeline:play("wait", false) local duration = UIHelper.getAnimationDuration(timeline local block = cc.CallFunc:create( function(sender) callBack() end ) self:runAction(cc.Sequence:create(cc.DelayTime:create(duration), block))
通過UIHelper.getAnimationDuration方法獲取動畫執行的時間:
function UIHelper.getAnimationDuration(timeline) local speed = timeline:getTimeSpeed() -- local duration = timeline:getDuration() local startFrame = timeline:getStartFrame() local endFrame = timeline:getEndFrame() local frameNum = endFrame - startFrame return 1.0 /(speed * 60.0) * frameNum end
這樣的方法雖然增加一些程式碼,但減少因編輯器經常更新而造成的問題
完整的UIHelper.lua如下:
UIHelper = {}
-- tolua.cast(ccsLayout:getChildByName("server_list") ,"ListView") .
function UIHelper.getControl(root,parentNames)
local newRoot = root
for i = 1,#parentNames do
local name = parentNames[i]
local child = newRoot:getChildByName(name)
if not child then
newRoot = nil
break
else
newRoot = child
end
end
return newRoot
end
function UIHelper.createNode(parent,file,pos)
local layout = cc.CSLoader:createNode(file)
if pos then layout:setPosition(pos) end
parent:addChild(layout)
local timeline = cc.CSLoader:createTimeline(file)
layout:runAction(timeline)
return layout,timeline
end
function UIHelper.getAnimationDuration(timeline)
local speed = timeline:getTimeSpeed()
-- local duration = timeline:getDuration()
local startFrame = timeline:getStartFrame()
local endFrame = timeline:getEndFrame()
local frameNum = endFrame - startFrame
return 1.0 /(speed * 60.0) * frameNum
end
function UIHelper.runTimeline(layout,timeline, animationName,loop)
if not loop then loop = false end
if animationName ~= nil and timeline:IsAnimationInfoExists(animationName) then
timeline:play(animationName, loop)
else
timeline:gotoFrameAndPlay(0, loop)
end
end
--
function UIHelper.runTimelineAndClear(layout,timeline, animationName)
UIHelper.runAction(layout,timeline, animationName)
local duration = UIHelper.getAnimationDuration(timeline)
local block = cc.CallFunc:create( function(sender)
layout:removeSelf()
end )
layout:runAction(cc.Sequence:create(cc.DelayTime:create(duration), block))
end
function UIHelper.runTimelineAndCall(layout,timeline, animationName,callBack)
local duration = UIHelper.getAnimationDuration(timeline)
local block = cc.CallFunc:create( function(sender)
return callBack
end )
layout:runAction(cc.Sequence:create(cc.DelayTime:create(duration), block))
end
QQ群:239759131 cocos 技術交流 歡迎您