const MOVE_LEFT = 1; // 向左移动标志位
const MOVE_RIGHT = 2; // 向右移动标志位
cc.Class({
extends: cc.Component,
properties: {
maxSpeed: 1200
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
// 注册键盘按下和释放事件的回调
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
// 注册触摸事件的回调
var canvas = cc.find('/Canvas');
canvas.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
canvas.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.moveFlags = 0;
},
start () {
// start 在 onLoad 之后,此时RigidBody组件已经被加载进来
this.body = this.getComponent(cc.RigidBody);
},
onKeyDown(event) {
switch(event.keyCode) {
case cc.KEY.a:
case cc.KEY.left:
this.moveFlags |= MOVE_LEFT; // 添加向左移动的标志位
this.updateMotorSpeed();
break;
case cc.KEY.d:
case cc.KEY.right:
this.moveFlags |= MOVE_RIGHT; // 添加向右移动的标志位
this.updateMotorSpeed();
break;
}
},
onKeyUp (event) {
switch(event.keyCode) {
case cc.KEY.a:
case cc.KEY.left:
this.moveFlags &= ~MOVE_LEFT; // 清除向左移动标志
break;
case cc.KEY.d:
case cc.KEY.right:
this.moveFlags &= ~MOVE_RIGHT; // 清除向右移动标志
break;
}
},
onTouchStart: function(event) {
let touchLoc = event.touch.getLocation();
if (touchLoc.x < cc.winSize.width/2) {
this.moveFlags |= MOVE_LEFT; // 添加向左移动的标志位
} else {
this.moveFlags |= MOVE_RIGHT; // 添加向右移动的标志位
}
this.updateMotorSpeed();
},
onTouchEnd: function(event) {
let touchLoc = event.touch.getLocation();
if (touchLoc.x < cc.winSize.width/2) {
this.moveFlags &= ~MOVE_LEFT; // 清除向左移动标志
} else {
this.moveFlags &= ~MOVE_RIGHT; // 清除向右移动标志
}
},
updateMotorSpeed() {
// 判断this.body是否可用
if (!this.body) {
return;
}
var desiredSpeed = 0;
if ((this.moveFlags & MOVE_LEFT) == MOVE_LEFT) {
desiredSpeed = -this.maxSpeed;
} else if ((this.moveFlags & MOVE_RIGHT) == MOVE_RIGHT) {
desiredSpeed = this.maxSpeed;
}
// 设置小球刚体角速度来控制小球的运动方向和速度
this.body.angularVelocity = desiredSpeed;
},
update (dt) {
// 判断标志位是否为空(避免在没有事件触发时也去改变小球运动)
if (this.moveFlags) {
this.updateMotorSpeed();
}
},
});
来源
https://blog.csdn.net/foupwang/article/details/79830731
网友评论