-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInputManager.js
87 lines (87 loc) · 2.66 KB
/
InputManager.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
import * as THREE from 'three';
import { updateStatus } from './utils';
import { World } from './world';
class InputManager {
/**
* @type {THREE.Raycaster}
*/
raycaster = new THREE.Raycaster();
/**
* @type {THREE.Camera}
*/
camera = null;
/**
* @type {World}
*/
world = null;
constructor() {
this.raycaster.layers.disable(1);
}
initialize(camera, world) {
this.camera = camera;
this.world = world;
}
/**
* Wait for the player to choose a target square
* @returns {Promise<Vector3 | null>}
*/
async getTargetSquare() {
updateStatus('Select a target square');
return new Promise((resolve) => {
/**
* Event handler when user clicks on the screen
* @param {MouseEvent} event
*/
const onMouseDown = (event) => {
const coords = new THREE.Vector2(
(event.clientX / window.innerWidth) * 2 - 1,
- (event.clientY / window.innerHeight) * 2 + 1
);
this.raycaster.setFromCamera(coords, this.camera);
const intersections = this.raycaster.intersectObject(this.world.terrain);
if (intersections.length > 0) {
const selectedCoords = new THREE.Vector3(
Math.floor(intersections[0].point.x),
0,
Math.floor(intersections[0].point.z)
);
window.removeEventListener('mousedown', onMouseDown);
resolve(selectedCoords);
}
};
// Wait for player to select a square
window.addEventListener('mousedown', onMouseDown);
});
}
/**
* Wait for the player to choose a target GameObject
* @returns {Promise<GameObject | null>}
*/
async getTargetObject() {
updateStatus('Select a target object');
return new Promise((resolve) => {
/**
* Event handler when user clicks on the screen
* @param {MouseEvent} event
*/
const onMouseDown = (event) => {
const coords = new THREE.Vector2(
(event.clientX / window.innerWidth) * 2 - 1,
- (event.clientY / window.innerHeight) * 2 + 1
);
this.raycaster.setFromCamera(coords, this.camera);
const intersections = this.raycaster.intersectObject(this.world.objects, true);
if (intersections.length > 0) {
// Intersection is occurring with the mesh
// The parent of the mesh is the GameObject
const selectedObject = intersections[0].object.parent;
window.removeEventListener('mousedown', onMouseDown);
resolve(selectedObject);
}
};
window.addEventListener('mousedown', onMouseDown);
});
}
}
const inputManager = new InputManager();
export default inputManager;