Nanfeng

Notes on software development, code, and curious ideas

Frame Animations in Cocos2d-x with Lua

Cocos2d-x 3.17 can play frame animation assembled in code or authored in a Cocos Studio timeline. Code is convenient for a simple sprite-sheet sequence; Studio is useful when animation involves several UI nodes and properties.

Build animation from a sprite sheet

Load the plist, collect frames in order, and create an action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
local cache = cc.SpriteFrameCache:getInstance()
cache:addSpriteFrames("animation/hero.plist")

local frames = {}
for index = 1, 12 do
local name = string.format("hero_%02d.png", index)
local frame = cache:getSpriteFrameByName(name)
assert(frame, "missing sprite frame: " .. name)
frames[#frames + 1] = frame
end

local sprite = cc.Sprite:createWithSpriteFrame(frames[1])
sprite:setPosition(display.cx, display.cy)
self:addChild(sprite)

local animation = cc.Animation:createWithSpriteFrames(frames, 0.08)
sprite:runAction(cc.RepeatForever:create(cc.Animate:create(animation)))

The interval is seconds per frame. Keep the plist and texture loaded for the lifetime of the animation, and remove them only after no live sprite or action uses their frames.

Play a Cocos Studio timeline

1
2
3
4
5
local node = cc.CSLoader:createNode("animation/scene.csb")
local timeline = cc.CSLoader:createTimeline("animation/scene.csb")
self:addChild(node)
node:runAction(timeline)
timeline:play("idle", true)

The named animation must exist in the exported CSB. Retain a reference to the node or timeline when later code needs to stop, switch, or inspect it.

Use atlases to reduce texture changes, but watch atlas size and memory. Choose an update interval that matches the artwork; duplicating frames to force a high timeline frame rate wastes data without creating smoother source animation.

+