iT邦幫忙

2026 iThome 鐵人賽

DAY 24
0

一、讓 3D 物件動起來

前幾天我們一步一步建立 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();

螢幕擷取畫面 2026-10-05 144306
螢幕擷取畫面 2026-10-05 144314
image

四、結論

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

下一篇,就來讓使用者真正和 3D 世界互動。


上一篇
Day23 為什麼我的 3D 世界看起來不好玩
下一篇
Day25 讓我們更熟悉3D 世界:用滑鼠控制它
系列文
JavaScript 從入門到進階:結合 Three.js × GSAP 打造互動網頁 共 25 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言