Cocos Creator(一)物体的移动和跳跃
程序员文章站
2024-03-16 23:18:40
...
cc.Class({
extends: cc.Component,
properties: {
jumpHeight: 200,
jumpDuration: 0.35,
xSpeed : 350,
},
onLoad () {
// 初始化键盘输入监听
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
},
start () {
},
update: function (dt) {
//根据当前速度方向每帧更新速度
if (this.accLeft) {
this.node.x -= this.xSpeed * dt;
} else if (this.accRight) {
this.node.x += this.xSpeed * dt;
}
},
onDestroy () {
// 取消键盘输入监听
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
},
//跳跃功能,在跳跃期间暂停跳跃功能
jumpAction (){
var jumpUp = cc.moveBy(this.jumpDuration, cc.v2(0,this.jumpHeight)).easing(cc.easeCubicActionOut())
var jumpDown = cc.moveBy(this.jumpDuration, cc.v2(0, -this.jumpHeight)).easing(cc.easeCubicActionIn());
var setJump=cc.callFunc(function(){this.isJump=false},this,this);
return cc.sequence(jumpUp,jumpDown,setJump);
},
onKeyDown (event) {
switch(event.keyCode) {
case cc.macro.KEY.a:
console.log(this.node.x)
this.accLeft = true;
break;
case cc.macro.KEY.d:
this.accRight = true;
break;
case cc.macro.KEY.w:
if(!this.isJump){
this.isJump = true;
this.node.runAction(this.jumpAction());
}
break;
}
},
onKeyUp (event) {
switch(event.keyCode) {
case cc.macro.KEY.a:
this.accLeft = false;
break;
case cc.macro.KEY.d:
this.accRight = false;
break;
}
},
});