首先明确,所谓的动画,就是将一组图片按照一定的顺序在一定的时间中播放出来。
首先将一张猴子精灵图拖动到场景编辑器中:
然后通过其属性检查器,可以看到当前精灵图存在一个 SpriteFrame
属性:
也就是说,如果我们想要实现猴子行走,只需要改变这个 SpriteFrame
属性的值即可。
在资源管理器窗口的assets目录下新建一个 monkeyWalkAnimation
脚本,然后来到层级管理器中,点击选中猴子精灵图,然后将资源管理器中的 monkeyWalkAnimation
脚本拖动到属性检查器的“添加组件”按钮上,为该精灵图添加脚本:
双击资源管理器中的 monkeyWalkAnimation
脚本,会在VSCode中打开该脚本文件(前提是安装了VSCode)。
首先对动画属性进行分析,控制这个动画需要如下属性:
- 动画播放速度:speed,number,默认值为0.1,表示1秒10帧;
- 帧动画数组:sprites,SpriteFrame,默认值为空数组,每一个元素代表1帧图片;
- 是否播放动画:isWalking,boolean,默认值为true;
- 当前播放帧下标:index,number,默认值为0,表示当前正在播放第几帧;
- 定时器:timer,number,默认值为0,用于判断是否需要播放下一帧;
其中,前面3个属性是可以被外部控制的,因此需要通过property装饰器进行装饰,目前代码如下:
import { _decorator, Component, Node, SpriteFrame, Sprite } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('monkeyWalkAnimantion')
export class monkeyWalkAnimantion extends Component {
@property({ type: Number, displayName: '动画速度' })
private speed: number = 0.1 // 1s10帧
@property({ type: SpriteFrame, displayName: '帧动画数组' })
private sprites: SpriteFrame[] = []
@property({ type: Boolean, displayName: '是否播放动画' })
private isWalking: boolean = true
private index: number = 0 // 当前播放帧下标
private timer: number = 0 // 计时器
start() {}
update(){}
}
此时,回到CocosCreator,会发现精灵图的属性检查器窗口多出来了几个配置项:
就是我们刚刚在代码中定义的属性,在帧动画数组后面输入3,表示该属性有3个元素,然后将资源管理器窗口的每一帧图片按顺序拖动到对应元素位置中即可。
然后回到VsCode中,完善update方法:
update(deltaTime: number) {
if (this.isWalking) {
// 播放动画
// 计时器增加
this.timer += deltaTime
if (this.timer >= this.speed) {
this.timer = 0
// 更改帧下标
this.index++
if (this.index >= this.sprites.length) {
this.index = 0 // 超出范围置零
}
// 更换帧图片
this.getComponent(Sprite).spriteFrame = this.sprites[this.index]
}
}
}
上面的代码中,要注意的就是:
this.getComponent(Sprite).spriteFrame = this.sprites[this.index]
这行代码的意思就是,获取当前精灵的spriteFrame属性,将其赋值为xxx值。
回到CocosCreator,点击顶部的预览,就可以看到猴子在走路了。