提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
在游戏开发中,动画系统是赋予角色和界面生命力的核心模块。本文通过Cocos Creator动画系统的三大核心组件(AnimationClip、Animation、AnimationState),结合旋转缩放动画、脚本控制、状态机切换等典型案例,深入浅出地讲解动画制作与控制的核心方法。无论是基础的关键帧录制,还是复杂的逻辑交互,都能通过系统化的学习快速掌握。
动画系统
- 动画剪辑(AnimationClip)
- 记录节点属性随时间变化的数据(如位置、旋转、透明度)
- 动画组件(Animation)
- 控制动画的播放、暂停、循环等
- 动画状态机(AnimationState)
- 管理多个动画的切换和混合
动画系统案例
案例1:编辑器制作旋转缩放动画
目标:用编辑器为图标制作持续旋转+周期性缩放的动画。
步骤:
- 创建动画剪辑
- 选中目标节点 → 点击编辑器下方 动画 面板 → 点击
新建 AnimationClip
并命名(如spin
)
- 选中目标节点 → 点击编辑器下方 动画 面板 → 点击
- 录制关键帧
- 时间轴移动到 0s → 点击红点开始录制 → 设置
Rotation Z
为 0 - 时间轴移动到 5s → 修改
Rotation Z
为 360 → 自动生成关键帧 - 同理,在 0s、2.5s、5s 处设置
Scale
为 (1,1,1) → (1.2,1.2,1) → (1,1,1)
- 时间轴移动到 0s → 点击红点开始录制 → 设置
- 配置动画组件
- 节点自动添加
Animation
组件 → 设置Default Clip
为spin
- 勾选
Play On Load
和Loop
- 节点自动添加
- 运行测试
- 图标会持续旋转并周期性缩放
案例2:脚本控制动画播放
目标:点击按钮播放/暂停动画。
代码:
import { _decorator, Component, Animation, Button } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('AnimControl')
export class AnimControl extends Component {
@property({ type: Animation })
targetAnim: Animation | null = null; // 关联动画组件
private isPlaying: boolean = true;
start() {
// 绑定按钮事件
this.node.getComponent(Button)?.node.on(Button.EventType.CLICK, this.toggleAnim, this);
}
toggleAnim() {
if (!this.targetAnim) return;
this.isPlaying ? this.targetAnim.pause() : this.targetAnim.play();
this.isPlaying = !this.isPlaying;
}
}
操作:
- 将脚本挂载到按钮节点
- 将动画节点拖拽到
targetAnim
属性 - 点击按钮切换动画状态
案例3:状态切换动画(跑酷游戏常用)
目标:通过键盘控制角色切换 idle/run 动画。
步骤:
- 准备两个动画剪辑
idle.anim
:站立呼吸动画run.anim
:奔跑动画
- 编写状态切换脚本
import { _decorator, Component, Animation, input, Input, KeyCode } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('CharacterAnim')
export class CharacterAnim extends Component {
private anim: Animation | null = null;
onLoad() {
this.anim = this.getComponent(Animation);
input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
}
onKeyDown(event: any) {
if (!this.anim) return;
switch(event.keyCode) {
case KeyCode.KEY_A:
case KeyCode.KEY_D:
this.anim.play('run'); // 播放奔跑动画
break;
case KeyCode.KEY_S:
this.anim.play('idle'); // 切回站立动画
break;
}
}
}
总结
从编辑器操作到脚本编程,动画系统的核心在于对时间轴与状态逻辑的掌控。通过本文案例,开发者可掌握关键帧录制、组件通信、事件监听等核心技能。任务设计紧密结合实际需求,如固定布局、动态列表、表单交互等场景,强化UI系统的综合应用能力。牢记常见问题排查方法,可大幅提升开发效率。动画不仅是视觉呈现,更是游戏逻辑的载体,灵活运用方能创造真正生动的交互体验。
本阶段任务
- 制作一个包含位置移动+渐隐渐现的动画剪辑
- 创建两个按钮分别控制播放不同动画(如攻击/受伤)
- 实现角色跳跃动画:空格键触发跳跃动画(使用
animation.crossFade
平滑过渡)
常见问题预解答:
- 动画不播放:检查动画剪辑是否关联到组件,是否被其他逻辑强制停止
- 关键帧不生效:确保录制时红点激活状态,属性变化幅度足够
- 动画闪烁:使用
crossFade
代替直接play
实现平滑过渡