playcanvas
Version:
Open-source WebGL/WebGPU 3D engine for the web
70 lines (69 loc) • 2.14 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { math } from "../../../core/math/math.js";
import { Vec2 } from "../../../core/math/vec2.js";
const v = new Vec2();
class VirtualJoystick {
/**
* @param {object} options - The options.
* @param {number} [options.range] - The inner max distance of the joystick.
*/
constructor({ range } = {}) {
/** @private */
__publicField(this, "_range", 70);
/** @private */
__publicField(this, "_position", new Vec2());
/** @private */
__publicField(this, "_value", new Vec2());
this._range = range ?? this._range;
}
/**
* The vector value of the joystick, normalized to the range of -1 to 1.
*
* @type {Vec2}
*/
get value() {
return this._value;
}
/**
* @param {number} x - The x position.
* @param {number} y - The y position.
* @returns {number[]} - An array containing the base and stick positions.
*/
down(x, y) {
this._position.set(x, y);
this._value.set(0, 0);
return [x, y, x, y];
}
/**
* @param {number} x - The x position of the stick
* @param {number} y - The y position of the stick
* @returns {number[]} - An array containing the base and stick positions.
*/
move(x, y) {
v.set(x - this._position.x, y - this._position.y);
if (v.length() > this._range) {
v.normalize().mulScalar(this._range);
}
this._value.set(
math.clamp(v.x / this._range, -1, 1),
math.clamp(v.y / this._range, -1, 1)
);
const { x: bx, y: by } = this._position;
return [bx, by, bx + v.x, by + v.y];
}
/**
* Resets the joystick to its initial state.
*
* @returns {number[]} - An array containing the base and stick positions, both set to -1.
*/
up() {
this._position.set(0, 0);
this._value.set(0, 0);
return [-1, -1, -1, -1];
}
}
export {
VirtualJoystick
};