Skip to content

Instantly share code, notes, and snippets.

@jedy
Last active December 14, 2015 15:08
Show Gist options
  • Save jedy/5105356 to your computer and use it in GitHub Desktop.
Save jedy/5105356 to your computer and use it in GitHub Desktop.
创建cocos2d逐帧动画脚本
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import plistlib
import sys
import os.path
import re
def usage():
program = sys.argv[0]
print(program, "plist_file [plist_file...] prefix:duration [prefix:duration...]")
print("""
搜索所有plist_file中名字为prefix[\d_]+的精灵帧,
并将前缀相同的精灵帧按名字的顺序设为一个动画,动画名为prefix
生成出来的文件还可以按需求自行修改loops, setRestoreOriginalFrame, delayPerUnit等动画参数
以及spritesheets的名字""")
def create_animations(params):
spritesheets, params = seperate_argv(params)
frames = load_plist(spritesheets)
animations = {}
need_sheets = set()
for p in params:
animation, sheets = create_animation(frames, p)
if animation:
animations[animation["name"]] = animation["animation"]
need_sheets.update(sheets)
print(create_plist(spritesheets, animations))
def seperate_argv(argv):
sheets = []
params = []
for a in argv:
if a.lower().endswith(".plist"):
sheets.append(a)
else:
params.append(a.split(":"))
return sheets, params
def load_plist(sheets):
frames = {}
for f in sheets:
sheet = plistlib.readPlist(f)
if "frames" not in sheet:
continue
for k in sheet["frames"].iterkeys():
frames[k] = f
return frames
def create_animation(all_frames, p):
need_sheets = set()
animation_frames = []
pattern = re.compile(p[0] + "[\d_]+")
for frame, sheet in all_frames.iteritems():
if pattern.match(frame):
need_sheets.add(sheet)
animation_frames.append({"spriteframe": frame, "delayUnits": 1.0})
if not animation_frames:
return None, None
animation = {
"loops": 1,
"restoreOriginalFrame": True,
"frames": sorted(animation_frames, key=lambda x: x["spriteframe"]),
"delayPerUnit": float(p[1]) / len(animation_frames),
}
return {"name": p[0], "animation": animation}, need_sheets
def create_plist(sheets, animations):
sheet_names = []
for s in sheets:
s = os.path.abspath(s)
idx = s.find("Resources/")
if idx != -1:
sheet_names.append(s[idx + len("Resources/"):])
else:
sheet_names.append(os.path.basename(s))
plist = {"animations": animations, "properties": {"format": 2, "spritesheets": sheet_names}}
return plistlib.writePlistToString(plist)
if __name__ == "__main__":
if len(sys.argv) <= 1:
usage()
else:
create_animations(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment