-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjoystick.js
92 lines (74 loc) · 2.76 KB
/
joystick.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
88
89
90
91
92
class Joystick {
constructor(container) {
this.container = container;
this.handle = container.querySelector(".joystick-handle");
this.centerX = container.offsetWidth / 2;
this.centerY = container.offsetHeight / 2;
this.maxDistance = container.offsetWidth / 2 - this.handle.offsetWidth / 2;
this.isMoving = false;
this.currentAngle = 0;
this.currentDistance = 0;
this.moveCallback = null;
this.bindEvents();
}
bindEvents() {
this.handle.addEventListener("mousedown", this.startMove.bind(this));
document.addEventListener("mousemove", this.move.bind(this));
document.addEventListener("mouseup", this.endMove.bind(this));
this.handle.addEventListener("touchstart", this.startMove.bind(this));
document.addEventListener("touchmove", this.move.bind(this));
document.addEventListener("touchend", this.endMove.bind(this));
document.addEventListener("touchcancel", this.endMove.bind(this));
}
startMove(event) {
event.preventDefault();
this.isMoving = true;
}
move(event) {
if (!this.isMoving) return;
const { clientX, clientY } = event.touches ? event.touches[0] : event;
const rect = this.container.getBoundingClientRect();
const x = clientX - rect.left - this.centerX;
const y = clientY - rect.top - this.centerY;
const angle = Math.atan2(y, x);
const distance = Math.min(Math.hypot(x, y), this.maxDistance);
this.setPosition(angle, distance);
if (this.moveCallback) {
this.moveCallback(this.currentAngle, this.currentDistance);
}
}
endMove() {
this.isMoving = false;
this.setPosition(0, 0);
}
setPosition(angle, distance) {
this.currentAngle = angle;
this.currentDistance = distance;
const x = Math.cos(angle) * distance;
const y = Math.sin(angle) * distance;
this.handle.style.transform = `translate(${x}px, ${y}px)`;
}
onMove(callback) {
this.moveCallback = callback;
}
}
function joystickMoveListener() {
const joystickContainer = document.querySelector(".joystick-container");
const joystick = new Joystick(joystickContainer);
joystick.onMove((angle, distance) => {
// Calculate x and y changes based on the angle
let xChange = 0;
let yChange = 0;
if (angle >= 45 && angle < 135) {
yChange = -1; // Up
} else if (angle >= 135 && angle < 225) {
xChange = -1; // Left
} else if (angle >= 225 && angle < 315) {
yChange = 1; // Down
} else {
xChange = 1; // Right
}
// Call the handleArrowPress function with the calculated changes
handleArrowPress(xChange, yChange);
});
}