|
1 | 1 | import * as THREE from 'three';
|
| 2 | +import { FirstPersonControls } from 'three/examples/jsm/controls/FirstPersonControls'; |
2 | 3 |
|
| 4 | +// The scene object. |
3 | 5 | const scene = new THREE.Scene();
|
4 | 6 |
|
| 7 | +// Used to track time deltas. |
| 8 | +const clock = new THREE.Clock(); |
| 9 | + |
| 10 | +// Create a camera object. |
5 | 11 | const camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 1000);
|
6 | 12 | camera.position.z = 10;
|
7 | 13 |
|
| 14 | +// Create a renderer, append it to the document body. |
8 | 15 | const renderer = new THREE.WebGLRenderer({ antialias: true });
|
9 | 16 | renderer.setSize(window.innerWidth, window.innerHeight);
|
10 | 17 | renderer.setPixelRatio(window.devicePixelRatio);
|
11 | 18 | renderer.setClearColor(0x000000, 1);
|
12 | 19 |
|
13 |
| -document.body.appendChild(renderer.domElement); |
| 20 | +document.body.appendChild(renderer.domElement) |
| 21 | + |
| 22 | +// First person camera controller. |
| 23 | +const controls = new FirstPersonControls(camera, renderer.domElement); |
| 24 | +controls.movementSpeed = 5; |
| 25 | +controls.lookSpeed = 0.5; |
14 | 26 |
|
| 27 | +// Create a cube mesh with a geometry (shape) + material (color), add to scene. |
15 | 28 | const geometry = new THREE.BoxGeometry();
|
16 | 29 | const material = new THREE.MeshBasicMaterial({ color: 0x87E0FF });
|
17 | 30 | const cube = new THREE.Mesh(geometry, material);
|
18 | 31 |
|
19 |
| -console.log(cube); |
20 |
| - |
21 | 32 | scene.add(cube);
|
22 | 33 |
|
| 34 | +// Adjust renderer, aspect ratio on resize. |
| 35 | +window.addEventListener('resize', () => { |
| 36 | + renderer.setSize(window.innerWidth, window.innerHeight); |
| 37 | + camera.aspect = window.innerWidth / window.innerHeight; |
| 38 | + camera.updateProjectionMatrix(); |
| 39 | +}); |
| 40 | + |
| 41 | +// Core loop. |
23 | 42 | function animate() {
|
24 | 43 | requestAnimationFrame(animate);
|
| 44 | + |
| 45 | + controls.update(clock.getDelta()); |
25 | 46 | renderer.render(scene, camera);
|
| 47 | + |
26 | 48 | cube.rotation.x += 0.01;
|
27 | 49 | cube.rotation.y += 0.01;
|
28 | 50 | }
|
29 | 51 |
|
30 | 52 | animate();
|
31 |
| - |
32 |
| -function onWindowResize() { |
33 |
| - renderer.setSize(window.innerWidth, window.innerHeight); |
34 |
| - camera.aspect = window.innerWidth / window.innerHeight; |
35 |
| - camera.updateProjectionMatrix(); |
36 |
| -} |
37 |
| - |
38 |
| -window.addEventListener('resize', onWindowResize); |
|
0 commit comments