-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
337 lines (286 loc) · 9.29 KB
/
game.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/** Global variables */
let scene;
let camera;
let target;
let renderer;
let clock;
const bullets = [];
// const mouse = { x: 0, y: 0 };
// const hit = 0;
const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;
const keyboard = {};
const player = { height: 1.8, turnSpeed: Math.PI * 0.02, canShoot: 0 };
const blocker = document.getElementById('blocker');
const instructions = document.getElementById('instructions');
const havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
let controls;
/**
* Checks browser to see if cursor can be locked, locks cursor
* if so otherwise present error message.
* @param {boolean} havePointerLock - The boolean determining whether browser is
* capable of pointer lock.
* @return {None}
*/
function lockCursor() {
if (havePointerLock) {
const element = document.body;
const pointerlockchange = function () {
if (document.pointerLockElement === element || document.mozPointerLockElement === element
|| document.webkitPointerLockElement === element) {
controls.enabled = true;
blocker.style.display = 'none';
} else {
controls.enabled = false;
blocker.style.display = '-webkit-box';
blocker.style.display = '-moz-box';
blocker.style.display = 'box';
instructions.style.display = '';
}
};
const pointerlockerror = function () {
instructions.style.display = '';
};
// Hook pointer lock state change events
document.addEventListener('pointerlockchange', pointerlockchange, false);
document.addEventListener('mozpointerlockchange', pointerlockchange, false);
document.addEventListener('webkitpointerlockchange', pointerlockchange, false);
document.addEventListener('pointerlockerror', pointerlockerror, false);
document.addEventListener('mozpointerlockerror', pointerlockerror, false);
document.addEventListener('webkitpointerlockerror', pointerlockerror, false);
instructions.addEventListener('click', (event) => {
instructions.style.display = 'none';
// Ask the browser to lock the pointer
element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
if (/Firefox/i.test(navigator.userAgent)) {
var fullscreenchange = function (event) {
if (document.fullscreenElement === element || document.mozFullscreenElement === element || document.mozFullScreenElement === element) {
document.removeEventListener('fullscreenchange', fullscreenchange);
document.removeEventListener('mozfullscreenchange', fullscreenchange);
element.requestPointerLock();
}
};
document.addEventListener('fullscreenchange', fullscreenchange, false);
document.addEventListener('mozfullscreenchange', fullscreenchange, false);
element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen;
element.requestFullscreen();
} else {
element.requestPointerLock();
}
}, false);
} else {
instructions.innerHTML = 'Your browser doesn\'t seem to support Pointer Lock API';
}
}
/**
* Randomizes location of target to click
* @param {int} min - The int specifying the min -- lower bound.
* @param {int} max - The int specifying the max -- lower bound.
* @return {number} Location of target
*/
export function getRandomLoc(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}
/**
* Randomizes size of target to click
* @param {int} min - The int specifying the min -- lower bound.
* @param {int} max - The int specifying the max -- lower bound.
* @return {number} Size of target
*/
export function getRandomSize(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Spawns THREE.js geometric target with position and size determined from
* getRandomLoc() and getRandomSize()
* @param {THREE} scene - The world instance of the game
* @return {None}
*/
function spawnTarget(scene) {
const geometry = new THREE.SphereGeometry(getRandomSize(0.2, 0.9), 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0xffbf00 });
target = new THREE.Mesh(geometry, material);
scene.add(target);
target.position.x += getRandomLoc(-10, 10);
target.position.y += getRandomLoc(1, 5);
target.position.z += getRandomLoc(0, 10);
scene.add(target);
}
/**
* Creates THREE.js geometric floor, walls, and ceiling to create scene
* of playing area
* @param {THREE} scene - The world instance of the game
* @return {None}
*/
function createSpace(scene) {
floor = new THREE.Mesh(
new THREE.PlaneGeometry(150, 150, 150, 150),
new THREE.MeshBasicMaterial({ color: 0xa9a9a9 }),
);
floor.rotation.x -= Math.PI / 2; // Rotate the floor 90 degrees
scene.add(floor);
wall1 = new THREE.Mesh(
new THREE.BoxGeometry(200, 40, 20),
new THREE.MeshBasicMaterial({ color: 0x282828 }),
);
wall1.position.y -= 1;
wall1.position.z += 20;
scene.add(wall1);
wall2 = new THREE.Mesh(
new THREE.BoxGeometry(20, 40, 200),
new THREE.MeshBasicMaterial({ color: 0x282828 }),
);
wall2.position.y -= 1;
wall2.position.x += 30;
scene.add(wall2);
wall3 = new THREE.Mesh(
new THREE.BoxGeometry(20, 40, 200),
new THREE.MeshBasicMaterial({ color: 0x282828 }),
);
wall3.position.y -= 1;
wall3.position.x -= 30;
scene.add(wall3);
wall4 = new THREE.Mesh(
new THREE.BoxGeometry(200, 40, 20),
new THREE.MeshBasicMaterial({ color: 0x606060 }),
);
wall4.position.y -= 1;
wall4.position.z -= 40;
scene.add(wall4);
ceiling = new THREE.Mesh(
new THREE.BoxGeometry(200, 1, 200),
new THREE.MeshBasicMaterial({ color: 0x484848 }),
);
ceiling.position.y += 40;
scene.add(ceiling);
}
/**
* Creates THREE.js player with THREE.js camera perspective and predetermined controls
* @param {THREE} scene - The world instance of the game
* @return {None}
*/
function createPlayer(scene) {
camera.position.set(0, player.height, -5);
camera.lookAt(new THREE.Vector3(0, player.height, 0));
controls = new THREE.PointerLockControls(camera, document.body);
scene.add(controls.getObject());
}
/**
* Adds score to HUD
* @return {None}
*/
function addScore() {
$('body').append('<div id="hud"><p>Score: <span id="score">0</span></p></div>');
}
/**
* Renders THREE.js WebGL scene
* @param {THREE} scene - The world instance of the game
* @return {None}
*/
function render(scene) {
renderer = new THREE.WebGLRenderer();
renderer.setSize(WIDTH, HEIGHT);
document.body.appendChild(renderer.domElement);
}
/**
* Initializes the world, game, player, and targets
* @return {None}
*/
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 1000);
clock = new THREE.Clock();
createSpace(scene);
spawnTarget(scene);
addScore();
createPlayer(scene);
lockCursor(havePointerLock);
/* var reticle = new THREE.Mesh(
new THREE.RingBufferGeometry( 0.85 * 500, 500, 32),
new THREE.MeshBasicMaterial( {color: 0x000000, side: THREE.DoubleSide })
);
reticle.position.z = -4;
reticle.lookAt(camera.position);
camera.add(reticle);
scene.add(camera) */
render(scene);
animate();
}
/**
* Animates the scene
* @return {None}
*/
function animate() {
requestAnimationFrame(animate);
target.rotation.x += 0.01;
target.rotation.y += 0.02;
trackBullets();
renderer.render(scene, camera);
}
/**
* Detects when a key has been pressed down
* @param {event} event - Keyboard event
* @return {None}
*/
function keyDown(event) {
keyboard[event.keyCode] = true;
}
/**
* Detects when mouse is clicked down
* @return {None}
*/
document.body.onmousedown = function () {
const bullet = new THREE.Mesh(
new THREE.SphereGeometry(0.05, 8, 8),
new THREE.MeshBasicMaterial({ color: 0xffffff }),
);
bullet.position.set(0, player.height, -5);
bullet.velocity = new THREE.Vector3(-Math.sin(camera.rotation.y), 0, Math.cos(camera.rotation.y));
bullet.alive = true;
setTimeout(() => {
bullet.alive = false;
scene.remove(bullet);
}, 1000);
bullets.push(bullet);
scene.add(bullet);
player.canShoot = 10;
};
/**
* Keeps track of bullets array, removing bullets that miss
* @return {None}
*/
function trackBullets() {
for (let index = 0; index < bullets.length; index += 1) {
if (bullets[index] === undefined) {
continue;
}
if (bullets[index].alive == false) {
bullets.splice(index, 1);
continue;
}
bullets[index].position.add(bullets[index].velocity);
}
}
/**
* Detects when a key has been pressed down
* @param {event} event - Keyboard event
* @return {None}
*/
function keyUp(event) {
keyboard[event.keyCode] = false;
}
window.addEventListener('keydown', keyDown);
window.addEventListener('keyup', keyUp);
window.onload = init;
/**
* Handles window resizing
* @return {None}
*/
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener('resize', onWindowResize, false);