

@property(cc.Node)
public stick: cc.Node = null;
@property(cc.Node)
public joystickBackground: cc.Node = null;
private isTouching: boolean = false;
private maxDistance: number = 100;
private startPos: cc.Vec2 = new cc.Vec2();
static direction: cc.Vec2 = new cc.Vec2(0, 0);
onLoad() {
this.startPos = this.joystickBackground.convertToWorldSpace(cc.Vec2.ZERO);
this.joystickBackground.active = false;
}
start() {
Joystick.TouchScope.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
Joystick.TouchScope.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
Joystick.TouchScope.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
Joystick.TouchScope.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
}
- 在onload里记录摇杆初始位置,用来记录摇杆的偏移,this.joystickBackground.active是用来让摇杆显示和隐藏的,触摸的时候显示,停止触摸隐藏
onTouchStart(event: cc.Event.EventTouch) {
this.isTouching = true;
this.joystickBackground.active = true;
const touchPos = event.getLocation();
console.log(touchPos, 'touchPos');
const localPos = this.joystickBackground.parent.convertToNodeSpaceAR(touchPos);
this.joystickBackground.setPosition(localPos);
}
onTouchMove(event: cc.Event.EventTouch | cc.Vec2) {
if (!this.isTouching) return;
let touchPos: cc.Vec2;
if (event instanceof cc.Event.EventTouch) {
touchPos = event.getLocation();
} else {
touchPos = event;
}
let offset = touchPos.subtract(this.startPos);
const distance = offset.mag();
if (distance > this.maxDistance) {
offset = offset.normalize().multiplyScalar(this.maxDistance);
}
this.stick.setPosition(offset.x, offset.y);
Joystick.direction = new cc.Vec2(offset.x / this.maxDistance, offset.y / this.maxDistance);
}
onTouchEnd(event: cc.Event.EventTouch) {
this.isTouching = false;
this.joystickBackground.active = false;
this.stick.setPosition(0, 0);
Joystick.direction.set(new cc.Vec2(0, 0));
}
- 上面是触摸过程中的各个事件,开始触摸就确定好摇杆的位置,在触摸过程中记录方向,偏移量,让摇杆可以摇动,结束的时候还原
static getDirection() {
return Joystick.direction;
}
- 静态方法getDirection去获取移动的方向,提供给其他节点去使用
const direction = Joystick.getDirection();
this.node.setPosition(this.node.position.x + direction.x * this.speed * dt, this.node.position.y + direction.y * this.speed * dt);
- 在例如player里的update生命周期这里,根据direction来移动玩家