方向数组法:
设置四方向移动的状态数组dir = [0,0,0,0]用来判断移动方向(上下左右)
onLoad() {
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
dir = [0, 0, 0, 0];
this.schedule(this.keyMove, 0.1);
},
start() {
},
onKeyUp(event) {
switch (event.keyCode) {
default:
dir = [0, 0, 0, 0];
}
},
keyMove() {
if (dir[0] === 1) {
// anim.play("personUp");
this.node.y += 5;
}
else if (dir[1] === 1) {
// anim.play("personDown");
this.node.y -= 5;
}
else if (dir[2] === 1) {
// anim.play("personLeft");
this.node.x -= 5;
}
else if (dir[3] === 1) {
// anim.play("personRight");
this.node.x += 5;
}
},
onKeyDown(event) {
anim = this.node.getComponent(cc.Animation);
switch (event.keyCode) {
case cc.macro.KEY.a:
dir = [0, 0, 1, 0];
break;
case cc.macro.KEY.d:
dir = [0, 0, 0, 1];
break;
case cc.macro.KEY.w:
dir = [1, 0, 0, 0];
break;
case cc.macro.KEY.s:
dir = [0, 1, 0, 0];
break;
}
}
状态值法:
onLoad() {
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
},
start() {
this.state = null;
this.schedule(this.move, 0.01)
},
onKeyDown(e) {
if (this.keyState) return
switch (e.keyCode) {
case cc.macro.KEY.w: this.speedY = 5; this.state = cc.macro.KEY.w; break;
case cc.macro.KEY.a: this.speedX = -5; this.state = cc.macro.KEY.a; break;
case cc.macro.KEY.s: this.speedY = -5; this.state = cc.macro.KEY.s; break;
case cc.macro.KEY.d: this.speedX = 5; this.state = cc.macro.KEY.d; break;
}
},
onKeyUp(e) {
if(e.keyCode !== this.keyState) return
switch (e.keyCode) {
case cc.macro.KEY.w: this.speedY = 0;this.state = null; break;
case cc.macro.KEY.a: this.speedX = 0;this.state = null; break;
case cc.macro.KEY.s: this.speedY = 0;this.state = null; break;
case cc.macro.KEY.d: this.speedX = 0;this.state = null; break;
}
},
move() {
this.node.x += this.speedX;
this.node.y += this.speedY;
}