Hope someday I can build my own world like this.

Existing bug: When animations are added, we cannot add moving objects with a collision volume, still donno how to solve it.

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
<!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)

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


document.addEventListener ('mousedown', () => {
document.body.requestPointerLock ();
})
document.addEventListener ('mouseup', () => {

});
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 = 8.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)
// 那么end - start指定了该capsule的视角位置,一般也就指明了最高低点
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 -= 25 * delta;
damping *= 0.1;
}
velocity.addScaledVector (velocity, damping);

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 dracoloader = new DRACOLoader ();
dracoloader.setDecoderPath('./js/libs/draco/gltf/');

var mixer;

const loader = new GLTFLoader ();
loader.setDRACOLoader (dracoloader);
var model;
loader.load ('./models/gltf/LittlestTokyo.glb', function (gltf) {
model = gltf.scene;
model.position.set (0, 1, 0);
model.scale.set (0.04, 0.04, 0.04);
scene.add (model);

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

mixer = new THREE.AnimationMixer (model);
mixer.clipAction (gltf.animations[0]).play ();

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 ();

mixer.update (delta);

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

updatePlayer (delta);

stats.update ();

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