一、处理情景
用键盘和按钮控制角色的左右移动,涉及到的点:
1.左右移动时(人物转向),spriteFrame的切换;
2.移动时音频的调用;
3.鼠标键盘控制,类之间方法的调用。
二、场景和资源
三、处理方法
首先,处理左右移动时spriteFrame的切换。因此,要引入两个cc.SpriteFrame对象存储两种不同的spriteFrame。
然后,涉及到音频的调用,需要引入一个cc.AudioClip对象存储音频信息。
//用于存储向左和向右移动的SpriteFrame
@property(cc.SpriteFrame)
moveLeftSpriteFrame : cc.SpriteFrame = null
@property(cc.SpriteFrame)
moveRightSpriteFrame : cc.SpriteFrame = null
@property(cc.AudioClip)
audio : cc.AudioClip = null
最后,使用Cocos Creator的键盘按键事件和鼠标事件。Cocos Creator可接受的事件可参考《Cocos Creator的生命周期和支持的系统事件》
案例涉及到的核心代码:
所有代码:
Gamer Script文件
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.AudioClip)
audio : cc.AudioClip = null
@property(cc.SpriteFrame)
moveLeftSpriteFrame : cc.SpriteFrame = null
@property(cc.SpriteFrame)
moveRightSpriteFrame : cc.SpriteFrame = null
@property("number")
step : number = 20
// LIFE-CYCLE CALLBACKS:
onLoad () {
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDownForMove, this)
}
moveLeft() {
let gamerSprite : cc.Sprite = cc.find("Canvas/Gamer/toward").getComponent(cc.Sprite)
if(this.moveLeftSpriteFrame !== null) gamerSprite.spriteFrame = this.moveLeftSpriteFrame
this.node.x -= 20
if(this.audio !== null) cc.audioEngine.play(this.audio, false, 1)
}
moveRight() {
let gamerSprite : cc.Sprite = cc.find("Canvas/Gamer/toward").getComponent(cc.Sprite)
if(this.moveRightSpriteFrame !== null) gamerSprite.spriteFrame = this.moveRightSpriteFrame
this.node.x += 20
if(this.audio !== null) cc.audioEngine.play(this.audio, false, 1)
}
keyDownForMove(evt) {
if(evt.keyCode === 37) {
this.moveLeft()
} else if(evt.keyCode === 39) {
this.moveRight()
}
}
}
moveLeft Script文件(moveRight Script道理是一样的):
const {ccclass, property} = cc._decorator;
import GamerScript from "./Gmaer Script"
@ccclass
export default class MoveLeft extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
// LIFE-CYCLE CALLBACKS:
onLoad () {
this.node.on("mousedown", this.onMouseDown, this)
}
onMouseDown() {
let GamerClass = cc.find("Canvas/Gamer").getComponent(GamerScript)
GamerClass.moveLeft()
}
}
学习记录一下,如有错误和不足,欢迎各位大哥指正!