-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththree.html
354 lines (304 loc) · 14.4 KB
/
three.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
<!DOCTYPE html>
<html>
<head>
<title>Interactive 3D Environment</title>
<style>
body { margin: 0; background-color: #111; color: #fff; }
canvas { display: block; }
#controls { position: fixed; top: 10px; left: 10px; }
.button { margin-bottom: 5px; }
</style>
</head>
<body>
<div id="controls">
<button class="button" onclick="zoomIn()">Zoom In</button>
<button class="button" onclick="zoomOut()">Zoom Out</button>
<button class="button" onclick="resetView()">Reset View</button>
<!-- Additional controls can be added here -->
</div>
<script src="https://unpkg.com/[email protected]/build/three.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/controls/OrbitControls.js"></script>
<script>
let scene, camera, renderer, controls;
let cube, sphere, cone;
let highlightCube, highlightSphere, highlightCone;
let gridHelper;
let objects = [
{
mesh: cube,
targetPosition: new THREE.Vector3(),
animationId: null,
},
{
mesh: sphere,
targetPosition: new THREE.Vector3(),
animationId: null,
},
{
mesh: cone,
targetPosition: new THREE.Vector3(),
animationId: null,
},
];
function init() {
// Scene setup
scene = new THREE.Scene();
scene.background = new THREE.Color('black');
// Camera setup
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(5, 5, 5);
camera.lookAt(0, 0, 0);
// Renderer setup
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
// Orbit Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false;
// Grid Helper
gridHelper = new THREE.GridHelper(10, 10);
scene.add(gridHelper);
// Add basic shapes
addBasicShapes();
// Setup Player Controls+State
setupPlayerController();
// Add basic lightin
addBasicLighting();
// Add a basic orientation gizmo in the corner
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// Resize Listener
window.addEventListener('resize', onWindowResize, false);
// Render Loop
animate();
}
function addBasicLighting(){
// Ambient Light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Directional Light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 1, 0);
scene.add(directionalLight);
// Enable Shadows
directionalLight.castShadow = true;
// shadow map has no shadow?
// Shadow map settings
renderer.shadowMap.width = 1024; // default is 512
renderer.shadowMap.height = 1024; // default is 512
// directionalLight.shadow.mapSize.width = 1024; // default is 512
// directionalLight.shadow.mapSize.height = 1024; // default is 512
// ambientLight.shadow.mapSize.width = 1024; // default is 512
// ambientLight.shadow.mapSize.height = 1024; // default is 512
}
let playerState = {position:undefined}
let animationId = null;
let controllingObject = null;
let controllableObjects = [cube, sphere, cone]
let controllingObjectIndex = null;
const lerpSpeed = 0.1;
function setupPlayerController(){
document.addEventListener('keydown', (event) => {
const keyName = event.key;
// tab key = cycle through controllable objects
if(keyName === 'Tab'){
// find the index of the current controlling object
const currentIndex = controllableObjects.indexOf(controllingObject);
// set the next object in the array as the controlling object
changeControlledObject(controllableObjects[(currentIndex+1)%controllableObjects.length])
return;
}
if(!controllingObject){
return;
}
let metaObject = objects[controllingObjectIndex];
let targetPosition = metaObject.targetPosition;
controllingObject.getWorldPosition(targetPosition);
// optional mode: relative movement based on camera direction
const cameraDirection = new THREE.Vector3();
camera.getWorldDirection(cameraDirection);
cameraDirection.y = 0; // ignore y direction
cameraDirection.normalize();
switch(keyName){
case 'w':
targetPosition.add(cameraDirection.clone().round().multiplyScalar(1));
break;
case 's':
targetPosition.sub(cameraDirection.clone().round().multiplyScalar(1));
break;
case 'a':
targetPosition.sub(cameraDirection.clone().cross(new THREE.Vector3(0,1,0)).round().multiplyScalar(1));
break;
case 'd':
targetPosition.add(cameraDirection.clone().cross(new THREE.Vector3(0,1,0)).round().multiplyScalar(1));
break;
case ' ':
targetPosition.y += 1;
break;
case 'Shift':
targetPosition.y -= 1;
break;
}
// if the player's position is beyond the grid, constrain it to the grid
targetPosition.x = Math.min(Math.max(targetPosition.x, -5), 5);
targetPosition.z = Math.min(Math.max(targetPosition.z, -5), 5);
});
}
function changeControlledObject(next){
// disable "highlight" on the current object
highlightCube.visible = false;
highlightSphere.visible = false;
highlightCone.visible = false;
if(next === cube){
highlightCube.visible = true;
}
if(next === sphere){
highlightSphere.visible = true;
}
if(next === cone){
highlightCone.visible = true;
}
controllingObjectIndex = objects.findIndex((object) => object.mesh === next);
controllingObject = next;
console.warn('controlled object is now', next);
}
function addBasicShapes() {
// Cube
const cubeGeometry = new THREE.BoxGeometry();
const cubeMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });
cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.castShadow = true; // the cube will cast shadows
cube.receiveShadow = true; // the cube will receive shadows
cube.geometry.computeVertexNormals();
cube.position.y = cubeGeometry.parameters.height / 2; // make the cube float just above the ground
scene.add(cube);
objects[0].mesh = cube;
objects[0].targetPosition = cube.position.clone();
// Secondary Cube
const secondaryCubeGeometry = new THREE.BoxGeometry();
secondaryCubeGeometry.scale(1.1, 1.1, 1.1); // make it slightly larger
secondaryCubeGeometry.computeVertexNormals();
const secondaryCubeMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.BackSide }); // unlit and yellow
highlightCube = new THREE.Mesh(secondaryCubeGeometry, secondaryCubeMaterial);
highlightCube.visible = false; // initially hidden
// parent the highlight cube to the main cube
cube.add(highlightCube);
objects[0].higlightClone = highlightCube;
// Add click event to the cube
// Three.js does not have a built-in 'on' method for event handling
// Instead, we use the 'addEventListener' method of the HTML document object
// We also use a raycaster to detect the click on the cube
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
function onMouseClick(event) {
// calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// update the picking ray with the camera and mouse position
raycaster.setFromCamera(mouse, camera);
// calculate objects intersecting the picking ray
let intersects = raycaster.intersectObjects(scene.children);
for (let i = 0; i < intersects.length; i++) {
// Toggle visibility of secondary cube when the primary cube is clicked
if (intersects[i].object === cube) {
changeControlledObject(cube);
break;
}else if(intersects[i].object === sphere){
changeControlledObject(sphere);
break;
}else if(intersects[i].object === cone){
changeControlledObject(cone);
break;
}
}
}
// Add event listener for mouse click
window.addEventListener('click', onMouseClick, false);
// Sphere
const sphereGeometry = new THREE.SphereGeometry();
const sphereMaterial = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.x = 2;
sphere.castShadow = true; // the sphere will cast shadows
sphere.receiveShadow = true; // the sphere will receive shadows
sphere.geometry.computeVertexNormals();
sphere.position.y = sphereGeometry.parameters.radius; // make the sphere float just above the ground
scene.add(sphere);
objects[1].mesh = sphere;
objects[1].targetPosition = sphere.position.clone();
// clone as a yellow highlightSphere
const secondarySphereGeometry = new THREE.SphereGeometry();
secondarySphereGeometry.scale(1.1, 1.1, 1.1); // make it slightly larger
secondarySphereGeometry.computeVertexNormals();
const secondarySphereMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.BackSide }); // unlit and yellow
highlightSphere = new THREE.Mesh(secondarySphereGeometry, secondarySphereMaterial);
highlightSphere.visible = false; // initially hidden
sphere.add(highlightSphere);
objects[1].higlightClone = highlightSphere;
// Cone
const coneGeometry = new THREE.ConeGeometry(1, 2, 32);
const coneMaterial = new THREE.MeshPhongMaterial({ color: 0x0000ff });
cone = new THREE.Mesh(coneGeometry, coneMaterial);
cone.position.x = -2;
cone.castShadow = true; // the cone will cast shadows
cone.receiveShadow = true; // the cone will receive shadows
cone.geometry.computeVertexNormals();
cone.position.y = coneGeometry.parameters.height / 2; // make the cone float just above the ground
scene.add(cone);
objects[2].mesh = cone;
objects[2].targetPosition = cone.position.clone();
// add highlight cone
const secondaryConeGeometry = new THREE.ConeGeometry(1, 2, 32);
secondaryConeGeometry.scale(1.1, 1.1, 1.1); // make it slightly larger
secondaryConeGeometry.computeVertexNormals();
const secondaryConeMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.BackSide }); // unlit and yellow
highlightCone = new THREE.Mesh(secondaryConeGeometry, secondaryConeMaterial);
highlightCone.visible = false; // initially hidden
cone.add(highlightCone);
objects[2].higlightClone = highlightCone;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update(); // Only required if controls.enableDamping = true
// Loop through cube, sphere, cone independently
objects.forEach((object) => {
if (!object.mesh.position.equals(object.targetPosition)) {
object.mesh.position.lerp(object.targetPosition, lerpSpeed);
if (object.mesh.position.distanceTo(object.targetPosition) < 0.01) {
object.mesh.position.copy(object.targetPosition);
}
}
});
render();
}
function render() {
renderer.render(scene, camera);
}
function zoomIn() {
camera.zoom += 0.1;
camera.updateProjectionMatrix();
}
function zoomOut() {
camera.zoom -= 0.1;
camera.updateProjectionMatrix();
}
function resetView() {
camera.position.set(5, 5, 5);
camera.lookAt(0, 0, 0);
camera.zoom = 1;
camera.updateProjectionMatrix();
}
init();
</script>
</body>
</html>