前幾天我們一步一步建立 3D 世界。從 Scene、Camera、Renderer,到後來加入 Geometry、Material 和 Light,現在球體看起來已經有立體感了,但它還是一直停在原地不動。
今天就來讓它真的動起來。
Three.js 的物件可以使用 rotation 改變旋轉角度。
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
x 代表沿著 X 軸旋轉,y 則是沿著 Y 軸旋轉,但是如果只寫一次,畫面只會改變一次,但我們需要讓這段程式一直執行,所以會使用到requestAnimationFrame()。它會讓瀏覽器在準備更新下一個畫面時,再執行一次 animate()。
function animate() {
requestAnimationFrame(animate);
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
這是我們製作所需的 index.js。
import * as THREE from "three";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(
window.innerWidth,
window.innerHeight
);
document.body.appendChild(renderer.domElement)
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({
color: 0x8b5cf6
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const light = new THREE.DirectionalLight(0xffffff, 3);
light.position.set(3, 3, 5);
scene.add(light);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();



這次打開網頁,就會看到一個持續旋轉的紫色 3D 方塊,到這裡 Three.js 終於不只是建立靜態的 3D 畫面,而是真的開始動起來了,根本超級好玩啊!!!不過現在的動畫都是自己一直旋轉。如果我想用滑鼠控制 3D 世界,甚至讓使用者自己轉動物件呢?
下一篇,就來讓使用者真正和 3D 世界互動。