-
Notifications
You must be signed in to change notification settings - Fork 0
/
VirtualJoystick.js
87 lines (81 loc) · 3.06 KB
/
VirtualJoystick.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class VirtualJoystick {
/**
* @param {Phaser.Scene} scene Scene to add the virtual joystick to
* @param {number} x Coordinates to place the virtual joystick
* @param {number} y
* @param {number} radius The radius of the outer circle of the joystick
* @param {{base: number, stick: number, alpha: number}} colorConfig Object
* that is used to configure the color of the base and stick, and
* transparency of the overall joystick object
*/
constructor(scene, x, y, radius, colorConfig) {
// Base variables
this.scene = scene;
this.x = x;
this.y = y;
this.radius = radius;
this.colorConfig = colorConfig || {
base: 0xFFFFFF,
stick: 0xFF0000,
alpha: 0.4
}
// Outer circle, part that doesn't move
this.base = scene.add.circle(x, y, radius, this.colorConfig.base, this.colorConfig.alpha);
// Joystick circle
this.stick = scene.add.circle(x, y, .45 * radius, this.colorConfig.stick, this.colorConfig.alpha);
// Make the stick draggable
this.stick.setInteractive({ draggable: true });
scene.input.setDraggable(this.stick);
// Handle dragging the stick
scene.input.on('drag', (_, stick, dragX, dragY) => {
this.dragStick(stick, dragX, dragY);
});
scene.input.on('dragend', (_, stick) => {
this.resetStick(stick);
});
}
/**
* @returns Value ranging from -1 to 1 representing how far the stick is in
* the X direction
*/
joyX(){
return (this.stick.x - this.x) / this.radius;
}
/**
* @returns Value ranging from -1 to 1 representing how far the stick is in
* the Y direction
*/
joyY(){
return (this.stick.y - this.y) / this.radius;
}
/**
* Attempts to drag the stick to a given position, but restricts it based on radius
* @param {Phaser.GameObjects.Arc} stick The game object representing the stick
* @param {number} dragX X position being dragged to
* @param {number} dragY Y position being dragged to
*/
dragStick(stick, dragX, dragY) {
// Get the distance from center to drag point
let dist = Phaser.Math.Distance.Between(this.x, this.y, dragX, dragY);
// If we aren't outside the radius, move the stick to that position
if (dist < this.radius) {
stick.x = dragX;
stick.y = dragY;
}
// If we are outside the radius, move the stick towards the pointer but not on it
else {
let angle = Phaser.Math.Angle.Between(this.x, this.y, dragX, dragY);
let xRadius = Math.cos(angle) * this.radius;
let yRadius = Math.sin(angle) * this.radius;
stick.x = this.x + xRadius;
stick.y = this.y + yRadius;
}
}
/**
* Reset's the sticks position to the center
* @param {Phaser.GameObjects.Arc} stick The game object representing the stick
*/
resetStick(stick) {
stick.setPosition(this.x, this.y);
}
}