幀動畫實例html
下面咱們再看看具體的程序代碼,首先看一下看GameScene.lua文件,它的代碼以下:微信
[html] view plaincopy動畫
local isPlaying = false -- 播放標識 ① 網站
local size =cc.Director:getInstance():getWinSize() lua
… … spa
-- create layer .net
function GameScene:createLayer() orm
local layer = cc.Layer:create() 視頻
local spriteFrame = cc.SpriteFrameCache:getInstance() htm
spriteFrame:addSpriteFramesWithFile("run.plist")
local bg =cc.Sprite:createWithSpriteFrameName("background.png")
bg:setPosition(cc.p(size.width/2, size.height/2))
layer:addChild(bg)
local sprite = cc.Sprite:createWithSpriteFrameName("h1.png")
sprite:setPosition(cc.p(size.width/2, size.height/2))
layer:addChild(sprite)
--toggle菜單
local goSprite = cc.Sprite:createWithSpriteFrameName("go.png")
local stopSprite = cc.Sprite:createWithSpriteFrameName("stop.png")
local goToggleMenuItem = cc.MenuItemSprite:create(goSprite, goSprite)
local stopToggleMenuItem = cc.MenuItemSprite:create(stopSprite,stopSprite)
local toggleMenuItem = cc.MenuItemToggle:create(goToggleMenuItem,
stopToggleMenuItem)
toggleMenuItem:setPosition(cc.Director:getInstance():convertToGL(cc.p(930,540)))
local mn = cc.Menu:create(toggleMenuItem)
mn:setPosition(cc.p(0, 0))
layer:addChild(mn)
local function OnAction(menuItemSender)
if not isPlaying then
--///////////////動畫開始//////////////////////
local animation =cc.Animation:create() ②
for i=1,4 do
local frameName =string.format("h%d.png",i) ③
cclog("frameName =%s",frameName)
local spriteFrame = spriteFrame:getSpriteFrameByName(frameName) ④
animation:addSpriteFrame(spriteFrame) ⑤
end
animation:setDelayPerUnit(0.15) --設置兩個幀播放時間 ⑥
animation:setRestoreOriginalFrame(true) --動畫執行後還原初始狀態 ⑦
local action =cc.Animate:create(animation) ⑧
sprite:runAction(cc.RepeatForever:create(action)) ⑨
--//////////////////動畫結束///////////////////
isPlaying = true
else
sprite:stopAllActions() ⑩
isPlaying = false
end
end
toggleMenuItem:registerScriptTapHandler(OnAction)
return layer
end
return GameScene
上述代碼第①行是聲明一個布爾變量isPlaying,用來保存播放狀態,true時候說明正在播放,false時候說明中止播放。
第②行代碼是建立一個Animation對象,它是動畫對象,而後咱們要經過循環將各個幀圖片放到Animation對象中。第③行是得到幀圖片的文件名,string.format("h%d.png",i)是對字符串進行格式化。第④行代碼是經過幀名建立精靈幀對象,第⑤行代碼把精靈幀對象添加到Animation對象中。
第⑥行代碼是animation:setDelayPerUnit(0.15)是設置兩個幀播放時間,咱們這個動畫播放是4幀。第⑦行代碼animation:setRestoreOriginalFrame(true)是動畫執行完成是否還原到初始狀態。第⑧行代碼是經過一個Animation對象建立Animate對象,第⑨行代碼cc.Animate:create(animation)是執行動畫動做,無限循環方式。
第⑩行代碼sprite:stopAllActions()中止全部的動做。
更多內容請關注最新Cocos圖書《Cocos2d-x實戰:Lua卷——Cocos2d-lua開發》
本書交流討論網站:http://www.cocoagame.net
歡迎加入Cocos2d-x技術討論羣:257760386
更多精彩視頻課程請關注智捷課堂Cocos課程:http://v.51work6.com
智捷課堂現推出Cocos會員,敬請關注:http://v.51work6.com/courseInfoRedirect.do?action=netDetialInfo&courseId=844465&categoryId=0
《Cocos2d-x實戰 Lua卷》現已上線,各大商店均已開售:
京東:http://item.jd.com/11659697.html
歡迎關注智捷iOS課堂微信公共平臺,瞭解最新技術文章、圖書、教程信息