forked from Soft8Soft/verge3d-code-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
games_fps.html
499 lines (300 loc) · 12.5 KB
/
games_fps.html
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<!DOCTYPE html>
<html lang="en">
<head>
<title>Verge3D - misc - octree collisions</title>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
Octree threejs demo - basic collisions with static triangle mesh<br />
MOUSE to look around and to throw balls<br/>
WASD to move and SPACE to jump
</div>
<div id="container"></div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"v3d": "../build/v3d.module.js",
"v3d/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as v3d from 'v3d';
import Stats from 'v3d/addons/libs/stats.module.js';
import { GLTFLoader } from 'v3d/addons/loaders/GLTFLoader.js';
import { Octree } from 'v3d/addons/math/Octree.js';
import { OctreeHelper } from 'v3d/addons/helpers/OctreeHelper.js';
import { Capsule } from 'v3d/addons/math/Capsule.js';
import { GUI } from 'v3d/addons/libs/lil-gui.module.min.js';
const clock = new v3d.Clock();
const scene = new v3d.Scene();
scene.background = new v3d.Color(0x88ccee);
scene.fog = new v3d.Fog(0x88ccee, 0, 50);
const camera = new v3d.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.rotation.order = 'YXZ';
const fillLight1 = new v3d.HemisphereLight(0x4488bb, 0x002244, 0.5);
fillLight1.position.set(2, 1, 1);
scene.add(fillLight1);
const directionalLight = new v3d.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(- 5, 25, -1);
directionalLight.castShadow = true;
directionalLight.shadow.camera.near = 0.01;
directionalLight.shadow.camera.far = 500;
directionalLight.shadow.camera.right = 30;
directionalLight.shadow.camera.left = -30;
directionalLight.shadow.camera.top = 30;
directionalLight.shadow.camera.bottom = -30;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.radius = 4;
directionalLight.shadow.bias = -0.00006;
scene.add(directionalLight);
const container = document.getElementById('container');
const renderer = new v3d.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = v3d.VSMShadowMap;
renderer.outputEncoding = v3d.sRGBEncoding;
renderer.toneMapping = v3d.ACESFilmicToneMapping;
container.appendChild(renderer.domElement);
const stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
const GRAVITY = 30;
const NUM_SPHERES = 100;
const SPHERE_RADIUS = 0.2;
const STEPS_PER_FRAME = 5;
const sphereGeometry = new v3d.IcosahedronGeometry(SPHERE_RADIUS, 5);
const sphereMaterial = new v3d.MeshLambertMaterial({ color: 0xbbbb44 });
const spheres = [];
let sphereIdx = 0;
for (let i = 0; i < NUM_SPHERES; i++) {
const sphere = new v3d.Mesh(sphereGeometry, sphereMaterial);
sphere.castShadow = true;
sphere.receiveShadow = true;
scene.add(sphere);
spheres.push({
mesh: sphere,
collider: new v3d.Sphere(new v3d.Vector3(0, -100, 0), SPHERE_RADIUS),
velocity: new v3d.Vector3()
});
}
const worldOctree = new Octree();
const playerCollider = new Capsule(new v3d.Vector3(0, 0.35, 0), new v3d.Vector3(0, 1, 0), 0.35);
const playerVelocity = new v3d.Vector3();
const playerDirection = new v3d.Vector3();
let playerOnFloor = false;
let mouseTime = 0;
const keyStates = {};
const vector1 = new v3d.Vector3();
const vector2 = new v3d.Vector3();
const vector3 = new v3d.Vector3();
document.addEventListener('keydown', (event) => {
keyStates[event.code] = true;
});
document.addEventListener('keyup', (event) => {
keyStates[event.code] = false;
});
container.addEventListener('mousedown', () => {
document.body.requestPointerLock();
mouseTime = performance.now();
});
document.addEventListener('mouseup', () => {
if (document.pointerLockElement !== null) throwBall();
});
document.body.addEventListener('mousemove', (event) => {
if (document.pointerLockElement === document.body) {
camera.rotation.y -= event.movementX / 500;
camera.rotation.x -= event.movementY / 500;
}
});
window.addEventListener('resize', onWindowResize);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function throwBall() {
const sphere = spheres[sphereIdx];
camera.getWorldDirection(playerDirection);
sphere.collider.center.copy(playerCollider.end).addScaledVector(playerDirection, playerCollider.radius * 1.5);
// throw the ball with more force if we hold the button longer, and if we move forward
const impulse = 15 + 30 * (1 - Math.exp((mouseTime - performance.now()) * 0.001));
sphere.velocity.copy(playerDirection).multiplyScalar(impulse);
sphere.velocity.addScaledVector(playerVelocity, 2);
sphereIdx = (sphereIdx + 1) % spheres.length;
}
function playerCollisions() {
const result = worldOctree.capsuleIntersect(playerCollider);
playerOnFloor = false;
if (result) {
playerOnFloor = result.normal.y > 0;
if (!playerOnFloor) {
playerVelocity.addScaledVector(result.normal, - result.normal.dot(playerVelocity));
}
playerCollider.translate(result.normal.multiplyScalar(result.depth));
}
}
function updatePlayer(deltaTime) {
let damping = Math.exp(- 4 * deltaTime) -1;
if (!playerOnFloor) {
playerVelocity.y -= GRAVITY * deltaTime;
// small air resistance
damping *= 0.1;
}
playerVelocity.addScaledVector(playerVelocity, damping);
const deltaPosition = playerVelocity.clone().multiplyScalar(deltaTime);
playerCollider.translate(deltaPosition);
playerCollisions();
camera.position.copy(playerCollider.end);
}
function playerSphereCollision(sphere) {
const center = vector1.addVectors(playerCollider.start, playerCollider.end).multiplyScalar(0.5);
const sphere_center = sphere.collider.center;
const r = playerCollider.radius + sphere.collider.radius;
const r2 = r * r;
// approximation: player = 3 spheres
for (const point of [playerCollider.start, playerCollider.end, center]) {
const d2 = point.distanceToSquared(sphere_center);
if (d2 < r2) {
const normal = vector1.subVectors(point, sphere_center).normalize();
const v1 = vector2.copy(normal).multiplyScalar(normal.dot(playerVelocity));
const v2 = vector3.copy(normal).multiplyScalar(normal.dot(sphere.velocity));
playerVelocity.add(v2).sub(v1);
sphere.velocity.add(v1).sub(v2);
const d = (r - Math.sqrt(d2)) / 2;
sphere_center.addScaledVector(normal, - d);
}
}
}
function spheresCollisions() {
for (let i = 0, length = spheres.length; i < length; i++) {
const s1 = spheres[i];
for (let j = i + 1; j < length; j ++) {
const s2 = spheres[j];
const d2 = s1.collider.center.distanceToSquared(s2.collider.center);
const r = s1.collider.radius + s2.collider.radius;
const r2 = r * r;
if (d2 < r2) {
const normal = vector1.subVectors(s1.collider.center, s2.collider.center).normalize();
const v1 = vector2.copy(normal).multiplyScalar(normal.dot(s1.velocity));
const v2 = vector3.copy(normal).multiplyScalar(normal.dot(s2.velocity));
s1.velocity.add(v2).sub(v1);
s2.velocity.add(v1).sub(v2);
const d = (r - Math.sqrt(d2)) / 2;
s1.collider.center.addScaledVector(normal, d);
s2.collider.center.addScaledVector(normal, - d);
}
}
}
}
function updateSpheres(deltaTime) {
spheres.forEach(sphere => {
sphere.collider.center.addScaledVector(sphere.velocity, deltaTime);
const result = worldOctree.sphereIntersect(sphere.collider);
if (result) {
sphere.velocity.addScaledVector(result.normal, - result.normal.dot(sphere.velocity) * 1.5);
sphere.collider.center.add(result.normal.multiplyScalar(result.depth));
} else {
sphere.velocity.y -= GRAVITY * deltaTime;
}
const damping = Math.exp(- 1.5 * deltaTime) -1;
sphere.velocity.addScaledVector(sphere.velocity, damping);
playerSphereCollision(sphere);
});
spheresCollisions();
for (const sphere of spheres) {
sphere.mesh.position.copy(sphere.collider.center);
}
}
function getForwardVector() {
camera.getWorldDirection(playerDirection);
playerDirection.y = 0;
playerDirection.normalize();
return playerDirection;
}
function getSideVector() {
camera.getWorldDirection(playerDirection);
playerDirection.y = 0;
playerDirection.normalize();
playerDirection.cross(camera.up);
return playerDirection;
}
function controls(deltaTime) {
// gives a bit of air control
const speedDelta = deltaTime * (playerOnFloor ? 25 : 8);
if (keyStates['KeyW']) {
playerVelocity.add(getForwardVector().multiplyScalar(speedDelta));
}
if (keyStates['KeyS']) {
playerVelocity.add(getForwardVector().multiplyScalar(-speedDelta));
}
if (keyStates['KeyA']) {
playerVelocity.add(getSideVector().multiplyScalar(-speedDelta));
}
if (keyStates['KeyD']) {
playerVelocity.add(getSideVector().multiplyScalar(speedDelta));
}
if (playerOnFloor) {
if (keyStates['Space']) {
playerVelocity.y = 15;
}
}
}
const loader = new GLTFLoader().setPath('./models/gltf/');
loader.load('collision-world.glb', (gltf) => {
scene.add(gltf.scene);
worldOctree.fromGraphNode(gltf.scene);
gltf.scene.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
if (child.material.map) {
child.material.map.anisotropy = 4;
}
}
});
const helper = new OctreeHelper(worldOctree);
helper.visible = false;
scene.add(helper);
const gui = new GUI({ width: 200 });
gui.add({ debug: false }, 'debug')
.onChange(function(value) {
helper.visible = value;
});
animate();
});
function teleportPlayerIfOob() {
if (camera.position.y <= -25) {
playerCollider.start.set(0, 0.35, 0);
playerCollider.end.set(0, 1, 0);
playerCollider.radius = 0.35;
camera.position.copy(playerCollider.end);
camera.rotation.set(0, 0, 0);
}
}
function animate() {
const deltaTime = Math.min(0.05, clock.getDelta()) / STEPS_PER_FRAME;
// we look for collisions in substeps to mitigate the risk of
// an object traversing another too quickly for detection.
for (let i = 0; i < STEPS_PER_FRAME; i++) {
controls(deltaTime);
updatePlayer(deltaTime);
updateSpheres(deltaTime);
teleportPlayerIfOob();
}
renderer.render(scene, camera);
stats.update();
requestAnimationFrame(animate);
}
</script>
</body>
</html>