原理
玩家操作摇杆的方向键,摇杆会根据玩家移动的位置,计算出将要运动的方向的向量并输出给角色,
角色在接收到输入的运动方向的向量后,将其与自身的速度进行计算,最后得出要移动位置。

实现摇杆组件

-
添加脚本。 新建脚本并命名为:Joystick.ts ,并将此脚本挂载到场景中的Joystick节点上。 -
实现摇杆中圆球移动。 这里默认圆球的初始位置为:(0, 0)。 onEnable() {
this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
}
private onTouchStart(event: EventTouch) {
event.getLocation(this._pointA);
}
private onTouchMove(event: EventTouch) {
event.getLocation(this._pointB)
const offset: Vec2 = this._pointB.subtract(this._pointA);
this.circle.setPosition(v3(offsetX, offsetY, 0));
}
private onTouchEnd(event: EventTouch) {
this.circle.setPosition(Vec3.ZERO);
}
添加圆球的移动边界
this._radius = this.node.getComponent(UITransform)!.width * 0.5 - this.circle.getComponent(UITransform)!.width * 0.5
private onTouchMove(event: EventTouch) {
event.getLocation(this._pointB)
const offset: Vec2 = this._pointB.subtract(this._pointA);
const move = offset.clampf(v2(-1.0, -1.0).multiplyScalar(this._radius), v2(1.0, 1.0).multiplyScalar(this._radius));
const radian = v2(1, 0).signAngle(move);
const maxOffsetX = Math.cos(radian) * this._radius;
const maxOffsetY = Math.sin(radian) * this._radius;
const distance = move.length()
this.circle.setPosition(this._radius < distance ? v3(maxOffsetX, maxOffsetY, 0) : v3(move.x, move.y, 0));
}

输出结果:
this.node.emit('move', move.normalize());
角色移动
-
创建角色节点。 将角色素材拖动到场景中,命名为Player 。创建脚本Player.ts ,将此脚本挂载到Player节点上。 -
移动控制 @property
speed: number = 100;
private _moveDirection: Vec2 | undefined;
public move(direction: Vec2) {
this._moveDirection = direction;
}
update(deltaTime: number) {
if (!this._moveDirection) return;
this.node.translate(v3(this._moveDirection.x*this.speed * deltaTime, this._moveDirection.y * this.speed * deltaTime, 0));
}
效果

素材下载 代码下载
|