Learn to use Three.js

Refer to the Collision World project in Three.js official examples to learn Three.js.

Existing problem: do not really know the calculation process of velocity in the sphere-sphere collision portion because of my physics level.

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
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Chill</title>
<style>
body { margin: 0; background-color: white; }
</style>
</head>
<body>
<script type="importmap">{ "imports": { "three": "../build/three.module.js" } }</script>
<script type = "module">
// 开启阴影投射的条件
// 1. 首先需要有能够造成阴影的光(比如directional light)
// 2. 其次renderer.shadowMap需要开启(即renderer.shadowMap.enabled = true)
// 3. 为了使阴影更舒缓,需要调整其类型(即renderer.shadowMap.type = ...)
// 4. 物体本身需要开启castShadow(即mesh.castShadow = true, mesh.receiveShadow = true)

// 如何解决碰撞问题?方法其一(Octree)
// 1. 将模型octree化
// 2. 使用capsule类来建立一个“我”,设定高度及碰撞半径
// 3. 之后通过其内置的capsuleIntersect函数来判定周围物体位置
// 4. 将velocity修改回退(result.normal * depth)
// 那么实现一个正确的碰撞与什么有关?
// - camera的near和far
// - capsule的radius
// - velocity的增加delta量与减少delta量(仍未清楚如何计算是否正确)

import * as THREE from 'three';
import Stats from './jsm/libs/stats.module.js';

import { OrbitControls } from './jsm/controls/OrbitControls.js';
import { FirstPersonControls } from './jsm/controls/FirstPersonControls.js';
import { PointerLockControls } from './jsm/controls/PointerLockControls.js';

// 设置室内光环境
import { RoomEnvironment } from './jsm/environments/RoomEnvironment.js';

import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from './jsm/loaders/DRACOLoader.js';

import { Capsule } from './jsm/math/Capsule.js';
import { Octree } from './jsm/math/Octree.js';
import { OctreeHelper } from './jsm/helpers/OctreeHelper.js';

const clock = new THREE.Clock ();

const stats = new Stats ();
document.body.appendChild (stats.dom);

const renderer = new THREE.WebGLRenderer ({ antialias: true });
renderer.setPixelRatio (window.devicePixelRatio);
renderer.setSize (window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.VSMShadowMap;
document.body.appendChild (renderer.domElement);
// renderer.setClearColor (0xffffff, 1.0);

const pmremGenerator = new THREE.PMREMGenerator (renderer);

const scene = new THREE.Scene ();
scene.background = new THREE.Color (0x88ccee);
scene.fog = new THREE.Fog (0x88ccee, 0, 50);
// scene.environment = pmremGenerator.fromScene (new RoomEnvironment (), 0.4).texture;

const directionalLight = new THREE.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 camera = new THREE.PerspectiveCamera (70, window.innerWidth / window.innerHeight, 0.1, 1000);
// camera.position.set (0, 0.35, 0);
camera.rotation.order = 'YXZ';

const light = new THREE.HemisphereLight (0x4488bb, 0x002244, 0.5);
light.position.set (2, 1, 1);
scene.add (light);


document.addEventListener ('mousedown', () => {
document.body.requestPointerLock ();
})
document.addEventListener ('mouseup', () => {
if (document.pointerLockElement != null)
sphereShooting ();
});
document.body.addEventListener ('mousemove', event => {
if (document.pointerLockElement == document.body) {
camera.rotation.y -= event.movementX / 500;
camera.rotation.x -= event.movementY / 500;
}
});


var velocity = new THREE.Vector3 ();
var direction = new THREE.Vector3 ();
var moveForward = false, moveBackward = false, moveLeft = false, moveRight = false;
/*
const pointerControls = new PointerLockControls (camera, renderer.domElement);
document.body.addEventListener( 'click', function () { // 必须要lock状态下才可移动视角
pointerControls.lock();
} );
*/
var playerOnFloor = true;
const onKeyDown = function ( event ) {
switch ( event.code ) {
case 'ArrowUp':
case 'KeyW':
moveForward = true;
break;

case 'ArrowLeft':
case 'KeyA':
moveLeft = true;
break;

case 'ArrowDown':
case 'KeyS':
moveBackward = true;
break;

case 'ArrowRight':
case 'KeyD':
moveRight = true;
break;

case 'Space':
if (playerOnFloor == true) velocity.y = 15.0;
break;
}
};
const onKeyUp = function ( event ) {
switch ( event.code ) {
case 'ArrowUp':
case 'KeyW':
moveForward = false;
break;

case 'ArrowLeft':
case 'KeyA':
moveLeft = false;
break;

case 'ArrowDown':
case 'KeyS':
moveBackward = false;
break;

case 'ArrowRight':
case 'KeyD':
moveRight = false;
break;

}
};
document.addEventListener ('keydown', onKeyDown);
document.addEventListener ('keyup', onKeyUp);

const playerCollider = new Capsule (new THREE.Vector3 (0, 0.35, 0), new THREE.Vector3 (0, 1, 0), 0.35);
// Capsule (start, end, radius)
// start指代该capsule最低位,end为最高位,radius为半径
const worldOctree = new Octree ();

function forwardDirection () {
camera.getWorldDirection (direction); // 获取当前camera朝向方向的向量
return direction;
}
function sideDirection () {
camera.getWorldDirection (direction);
direction.cross (new THREE.Vector3 (0, 1, 0));
// 两个方向向量的乘积为他们的法向量,即返回我们正侧面的方向向量

return direction;
}
function updatePlayerVelocity (delta) {

// velocity.x -= velocity.x * 4.0 * delta;
// velocity.z -= velocity.z * 4.0 * delta;
// if (! playerOnFloor)
// velocity.y -= 9.8 * 2.0 * delta;

let damping = Math.exp (- 4 * delta) - 1;
if (! playerOnFloor) {
velocity.y -= 30 * delta;
damping *= 0.1;
}
velocity.addScaledVector (velocity, damping);
// 注意,这里用乘的速度才会无限趋近于0

let addspeed = playerOnFloor ? 20.0 : 8.0
if (moveForward)
velocity.add (forwardDirection ().multiplyScalar (addspeed * delta)); // multiplyScalar使向量乘以一个标量
if (moveBackward)
velocity.add (forwardDirection ().multiplyScalar (- addspeed * delta));
if (moveLeft)
velocity.add (sideDirection ().multiplyScalar (- addspeed * delta));
if (moveRight)
velocity.add (sideDirection ().multiplyScalar (addspeed * delta));
}
function playerCollision () {
const result = worldOctree.capsuleIntersect (playerCollider);

playerOnFloor = false;
if (result) {
playerOnFloor = result.normal.y > 0; // 注意跳起的时候result实际为undefined 因为没有与物体相交
// console.log (result.normal);
if (! playerOnFloor) {
velocity.addScaledVector (result.normal, - result.normal.dot (velocity));
// 空中撞墙原速反弹,若不加可能在空中会“粘”在天花板上
}
playerCollider.translate (result.normal.multiplyScalar (result.depth));
}
}
function updatePlayer (delta) {
updatePlayerVelocity (delta);

// start processing collision portion
let deltapos = new THREE.Vector3 (velocity.x * delta, velocity.y * delta, velocity.z * delta);
playerCollider.translate (deltapos); // start, end加上deltapos的值

playerCollision ();

camera.position.copy (playerCollider.end);
}

const spheres = [];
var n = 0;
const sphere_num = 100, sphere_radius = 0.2;

const sphereGeometry = new THREE.SphereGeometry (sphere_radius); // 二十面体,但第二参数大于1时为球体
const sphereMaterial = new THREE.MeshLambertMaterial ({ color: 0x00ffff });

for (let i = 1; i <= sphere_num; i ++) {
const sphereMesh = new THREE.Mesh (sphereGeometry, sphereMaterial);
sphereMesh.shadow = true;
sphereMesh.receiveShadow = true;

scene.add (sphereMesh);

spheres.push ({
mesh: sphereMesh,
collider: new THREE.Sphere (new THREE.Vector3 (0, - 100, 0), sphere_radius), // (pos of center, radius)
velocity: new THREE.Vector3 ()
});
}

function sphereShooting () {
const sphere = spheres[n];

camera.getWorldDirection (direction);
sphere.collider.center.copy (playerCollider.end).addScaledVector (direction, playerCollider.radius * 1.5);
sphere.velocity.copy (direction).multiplyScalar (30);

n = (n + 1) % spheres.length;
}
function updateSphereVelocity (sphere, delta) {
const damping = Math.exp (- 1.5 * delta) - 1;
sphere.velocity.addScaledVector (sphere.velocity, damping);
}
function sphereWallCollision (sphere, delta) {
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 -= 30 * delta;
}
const vec1 = new THREE.Vector3 (), vec2 = new THREE.Vector3 (), vec3 = new THREE.Vector3 ();
function playerSphereCollision (sphere) {
const playerCenter = vec1.addVectors (playerCollider.start, playerCollider.end).multiplyScalar (0.5);
// 人的中心在start与end之间
const r = playerCollider.radius + sphere.collider.radius;
const rSquared = r * r;

for (const point of [playerCollider.start, playerCollider.end, playerCenter]) {
const dist = point.distanceToSquared (sphere.collider.center);

if (dist < rSquared) {
// 碰撞与物理有关,搞不懂
const normal = vec1.subVectors (point, sphere.collider.center).normalize ();
const v1 = vec2.copy (normal).multiplyScalar (normal.dot (velocity));
const v2 = vec3.copy (normal).multiplyScalar (normal.dot (sphere.velocity));

velocity.add (v2).sub (v1);
sphere.velocity.add (v1).sub (v2);

const d = (r - Math.sqrt (dist)) / 2;

playerCollider.start.addScaledVector (normal, d);
playerCollider.end.addScaledVector (normal, d);
sphere.collider.center.addScaledVector (normal, - d);
}
}
}
function sphereSphereCollision () {
for (let i = 0; i < sphere_num; i ++) {
const sphere1 = spheres[i];
if (sphere1.collider.center.y == - 100) continue;
for (let j = i + 1; j < sphere_num; j ++) {
const sphere2 = spheres[j];
if (sphere2.collider.center.y == - 100) continue;

const dist = sphere1.collider.center.distanceToSquared (sphere2.collider.center);
const r = sphere1.collider.radius + sphere2.collider.radius;
const rSquared = r * r;

if (dist < rSquared) {
// 碰撞与物理有关,搞不懂
const normal = vec1.subVectors (sphere1.collider.center, sphere2.collider.center).normalize ();
const v1 = vec2.copy (normal).multiplyScalar (normal.dot (sphere1.velocity));
const v2 = vec3.copy (normal).multiplyScalar (normal.dot (sphere2.velocity));

sphere1.velocity.add (v2).sub (v1);
sphere2.velocity.add (v1).sub (v2);

const d = (r - Math.sqrt (dist)) / 2;

sphere1.collider.center.addScaledVector (normal, d);
sphere2.collider.center.addScaledVector (normal, - d);
}
}
}
}
function updateSpheres (delta) {
spheres.forEach (sphere => {
sphere.collider.center.addScaledVector (sphere.velocity, delta);

updateSphereVelocity (sphere, delta);
sphereWallCollision (sphere, delta);
playerSphereCollision (sphere);
});
sphereSphereCollision ();
spheres.forEach (sphere => {
sphere.mesh.position.copy (sphere.collider.center);
});
}

// -------------main-------------
const dracoloader = new DRACOLoader ();
dracoloader.setDecoderPath('./js/libs/draco/gltf/');

const loader = new GLTFLoader ();
loader.setDRACOLoader (dracoloader);
var model;
loader.load ('./models/gltf/collision-world.glb', function (gltf) {
model = gltf.scene;
scene.add (model);

worldOctree.fromGraphNode (gltf.scene);
model.traverse (child => {
if (child.isMesh) {
child.castShadow = true; // 当前mesh开启阴影投射
child.receiveShadow = true; // 当前mesh可以接收到别人的阴影
}
});

/*
const octreeHelper = new OctreeHelper (worldOctree);
octreeHelper.visible = false;
scene.add (octreeHelper);
*/

animate ();
}, undefined, function (error) {
console.log (error);
});

window.onresize = function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix ();

renderer.setSize (window.innerWidth, window.innerHeight);

// moveControls.handleResize ();
}

function animate () {
requestAnimationFrame (animate);

let delta = clock.getDelta ();

// orbitControls.update (delta);
// moveControls.update (delta);

updatePlayer (delta);
updateSpheres (delta);

stats.update ();

renderer.render (scene, camera);
}
</script>
</body>
</html>