質問するログイン新規登録

Q&A

解決済

1回答

217閲覧

Next.js&Three.jsでクリック時にアニメーションをつけたい

sgrgrgrgr

総合スコア1

Next.js

Next.jsは、Reactを用いたサーバサイドレンダリングなどを行う軽量なフレームワークです。Zeit社が開発しており、nextコマンドでプロジェクトを作成することにより、開発環境整備が整った環境が即時に作成できます。

Three.js

Three.jsはWebGLをサポートしているJavaScriptの3D描画用ライブラリです。

0グッド

0クリップ

投稿2026/11/19 20:41

編集2026/11/19 20:48

0

0

実現したいこと

Next.jsとThree.jsで3D空間に部屋を作り、
その部屋内にある扉をクリックすると開くようにしたいです。

発生している問題・分からないこと

クリックしても扉が回転しません。
consoleに"Clicked"という出力はされます。

該当のソースコード

TypeScript

1"use client"; 2 3import { useEffect, useRef } from "react"; 4import * as THREE from "three"; 5 6export default function RoomPage() { 7 // divを後から取得するための変数 8 const mountRef = useRef<HTMLDivElement>(null); 9 10 useEffect(() => { 11 // 描画先の div がまだ存在しないなら終了 12 if (!mountRef.current) return; 13 14 // シーン(3D空間)を作る 15 const scene = new THREE.Scene(); 16 17 // カメラを作る 18 const camera = new THREE.PerspectiveCamera( 19 75, // 視野角(FOV) 20 window.innerWidth / window.innerHeight, // 画面の縦横比 21 0.1, // 最小描画距離 22 1000 // 最大描画距離 23 ); 24 25 // レンダラーを作る 26 const renderer = new THREE.WebGLRenderer({ 27 antialias: true, 28 }); 29 // 描画サイズを画面いっぱいにする 30 renderer.setSize(window.innerWidth, window.innerHeight); 31 32 // <canvas>を作り、Reactのdivに追加 33 mountRef.current?.appendChild(renderer.domElement); 34 35 // 部屋 ------------------------------------------------------------------------------------------ 36 // 床 37 const floor = new THREE.Mesh( 38 new THREE.PlaneGeometry(18, 96), 39 new THREE.MeshStandardMaterial({ 40 color: 0x888888, 41 side: THREE.DoubleSide, 42 }) 43 ); 44 floor.rotation.x = -Math.PI / 2; 45 scene.add(floor); 46 47 // 天井 48 const ceiling = new THREE.Mesh( 49 new THREE.PlaneGeometry(18, 96), 50 new THREE.MeshStandardMaterial({ 51 color: 0x888888, 52 side: THREE.DoubleSide, 53 }) 54 ); 55 ceiling.rotation.x = Math.PI / 2; 56 ceiling.position.set(0, 48, 0); 57 scene.add(ceiling); 58 59 // 奥の壁 60 const backWall = new THREE.Mesh( 61 new THREE.PlaneGeometry(18, 48), 62 new THREE.MeshStandardMaterial({ 63 color: 0x444444, 64 side: THREE.DoubleSide 65 }) 66 ); 67 backWall.position.set(0, 24, -48); 68 scene.add(backWall); 69 70 // 左の壁 71 const leftWall = new THREE.Mesh( 72 new THREE.PlaneGeometry(96, 48), 73 new THREE.MeshStandardMaterial({ 74 color: 0x888888, 75 side: THREE.DoubleSide, 76 }) 77 ); 78 leftWall.rotation.y = Math.PI / 2; 79 leftWall.position.set(-9, 24, 0); 80 scene.add(leftWall); 81 82 // 右の壁 83 const rightWall = new THREE.Mesh( 84 new THREE.PlaneGeometry(96, 48), 85 new THREE.MeshStandardMaterial({ 86 color: 0x888888, 87 side: THREE.DoubleSide, 88 }) 89 ); 90 rightWall.rotation.y = -Math.PI / 2; 91 rightWall.position.set(9, 24, 0); 92 scene.add(rightWall); 93 94 // 扉 ------------------------------------------------------------------------------------------ 95 // 壁上部 96 const doorWallTop = new THREE.Mesh( 97 new THREE.BoxGeometry(18, 28, 1), 98 new THREE.MeshStandardMaterial({ 99 color: 0x444444, 100 side: THREE.DoubleSide 101 }) 102 ); 103 doorWallTop.position.set(0, 34, 0); 104 scene.add(doorWallTop); 105 106 // 壁左部 107 const doorWallLeft = new THREE.Mesh( 108 new THREE.BoxGeometry(4, 20, 1), 109 new THREE.MeshStandardMaterial({ 110 color: 0x444444, 111 side: THREE.DoubleSide 112 }) 113 ); 114 doorWallLeft.position.set(8, 10, 0); 115 scene.add(doorWallLeft); 116 117 // 壁右部 118 const doorWallRight = new THREE.Mesh( 119 new THREE.BoxGeometry(4, 20, 1), 120 new THREE.MeshStandardMaterial({ 121 color: 0x444444, 122 side: THREE.DoubleSide 123 }) 124 ); 125 doorWallRight.position.set(-8, 10, 0); 126 scene.add(doorWallRight); 127 128 // 左の扉 129 const leftDoor = new THREE.Mesh( 130 new THREE.BoxGeometry(6, 20, 0.5), 131 new THREE.MeshStandardMaterial({ 132 color: 0x5a3a22, 133 }) 134 ); 135 leftDoor.position.set(3, 10, 0); 136 scene.add(leftDoor); 137 console.log("create", leftDoor.uuid); 138 139 // 右の扉 140 const rightDoor = new THREE.Mesh( 141 new THREE.BoxGeometry(6, 20, 0.5), 142 new THREE.MeshStandardMaterial({ 143 color: 0x223a5a, 144 }) 145 ); 146 rightDoor.position.set(-3, 10, 0); 147 scene.add(rightDoor); 148 149 // 光 ------------------------------------------------------------------------------------------ 150 // 光源 151 const light = new THREE.DirectionalLight(0xffffff, 3); 152 light.position.set(0, 6, 48); 153 light.lookAt(0, 8, 24); 154 scene.add(light); 155 156 // 環境光 157 const ambientLight = new THREE.AmbientLight(0xffffff, 0.3); 158 scene.add(ambientLight); 159 160 const helper = new THREE.DirectionalLightHelper(light, 1, 0xffff00); 161 scene.add(helper); 162 163 // カメラ ------------------------------------------------------------------------------------------ 164 camera.position.set(-7, 6, 20); 165 camera.lookAt(0, 8, 0); 166 167 // Raycaster ------------------------------------------------------------------------------------------ 168 const raycaster = new THREE.Raycaster(); 169 const mouse = new THREE.Vector2(); 170 171 // イベント ------------------------------------------------------------------------------------------ 172 function onClick(event: MouseEvent) { 173 mouse.x = (event.clientX / window.innerWidth) * 2 - 1; 174 mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; 175 176 raycaster.setFromCamera(mouse, camera); 177 178 const intersects = raycaster.intersectObjects([ 179 leftDoor, 180 rightDoor, 181 ]); 182 183 if (intersects.length > 0) { 184 leftDoor.rotation.y = Math.PI / 2; 185 rightDoor.rotation.y = -Math.PI / 2; 186 } 187 188 console.log("Clicked"); 189 } 190 191 // イベント登録 192 window.addEventListener("click", onClick); 193 194 // アニメーション ------------------------------------------------------------------------------------------ 195 function animate() { 196 // 次のフレームでまたanimateを呼ぶ → 無限ループ 197 requestAnimationFrame(animate); 198 199 // 描画 200 renderer.render(scene, camera); 201 } 202 203 // アニメーション開始 204 animate(); 205 206 return () => { 207 // ページを離れた時の後始末 208 window.removeEventListener("click", onClick); 209 mountRef.current?.removeChild(renderer.domElement); 210 renderer.dispose(); 211 console.log( 212 "cleanup" 213 ); 214 }; 215 }, []); 216 217 return ( 218 <div 219 ref={mountRef} 220 style={{ 221 width: "100vw", 222 height: "100vh", 223 overflow: "hidden", 224 }} 225 /> 226 ); 227}

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

・Copilotに聞きながら作成しています

・animate内にleftDoor.rotation.y += 0.01;を記述すると、扉は回った

・初期値falseの変数isClickedを用意して、onClick内でtrueにし、animate内でisClicked === trueの時のみ、leftDoor.rotation.y += 0.01;を実行するようにしたが、扉は動かなかった

・animate内でconsole.log(leftDoor.rotation.y);を実行した時0と1.5707963267948966を交互に出力したが、扉は動かなかった

補足

初心者のため、暗黙の了解的なルールがあれば落としているかもしれません

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

guest

回答1件

0

自己解決

自己解決しました(原因と解決策)

お騒がせいたしました。
原因が特定でき、無事に解決しましたので同じ現象で悩む方の参考として残しておきます。

原因

React Strict Modeにより useEffect が2回実行されていたこと

  1. 1回目の実行で作られたシーン・扉と、2回目の実行で作られて画面に表示されているシーン・扉が別物になっていた。
  2. クリーンアップ時にrequestAnimationFrameが停止されておらず、裏で1回目のループが動き続けていた。

解決策

  1. useEffectの冒頭でmountRef.current.innerHTML = ""を実行し、既存のcanvasをクリアする。
  2. クリーンアップ処理(return () => { ... })内でcancelAnimationFrameを呼び出し、アニメーションループを確実に停止させる。
  3. マウス座標の計算基準をwindowではなくrenderer.domElement.getBoundingClientRect()に変更する。

修正後のコード

(ついでに扉の端を軸に滑らかに開くように THREE.Group で調整しました)

TypeScript

1"use client"; 2 3import { useEffect, useRef } from "react"; 4import * as THREE from "three"; 5 6export default function RoomPage() { 7 const mountRef = useRef<HTMLDivElement>(null); 8 9 useEffect(() => { 10 const container = mountRef.current; 11 if (!container) return; 12 13 // Strict Modeでの2重描画を防ぐため、既存のcanvasを削除 14 container.innerHTML = ""; 15 16 const scene = new THREE.Scene(); 17 18 const camera = new THREE.PerspectiveCamera( 19 75, 20 container.clientWidth / container.clientHeight, 21 0.1, 22 1000 23 ); 24 25 const renderer = new THREE.WebGLRenderer({ antialias: true }); 26 renderer.setSize(container.clientWidth, container.clientHeight); 27 container.appendChild(renderer.domElement); 28 29 // --- 部屋の作成 --- 30 const floor = new THREE.Mesh( 31 new THREE.PlaneGeometry(18, 96), 32 new THREE.MeshStandardMaterial({ color: 0x888888, side: THREE.DoubleSide }) 33 ); 34 floor.rotation.x = -Math.PI / 2; 35 scene.add(floor); 36 37 const ceiling = new THREE.Mesh( 38 new THREE.PlaneGeometry(18, 96), 39 new THREE.MeshStandardMaterial({ color: 0x888888, side: THREE.DoubleSide }) 40 ); 41 ceiling.rotation.x = Math.PI / 2; 42 ceiling.position.set(0, 48, 0); 43 scene.add(ceiling); 44 45 const backWall = new THREE.Mesh( 46 new THREE.PlaneGeometry(18, 48), 47 new THREE.MeshStandardMaterial({ color: 0x444444, side: THREE.DoubleSide }) 48 ); 49 backWall.position.set(0, 24, -48); 50 scene.add(backWall); 51 52 const leftWall = new THREE.Mesh( 53 new THREE.PlaneGeometry(96, 48), 54 new THREE.MeshStandardMaterial({ color: 0x888888, side: THREE.DoubleSide }) 55 ); 56 leftWall.rotation.y = Math.PI / 2; 57 leftWall.position.set(-9, 24, 0); 58 scene.add(leftWall); 59 60 const rightWall = new THREE.Mesh( 61 new THREE.PlaneGeometry(96, 48), 62 new THREE.MeshStandardMaterial({ color: 0x888888, side: THREE.DoubleSide }) 63 ); 64 rightWall.rotation.y = -Math.PI / 2; 65 rightWall.position.set(9, 24, 0); 66 scene.add(rightWall); 67 68 // --- 扉周りの壁 --- 69 const doorWallTop = new THREE.Mesh( 70 new THREE.BoxGeometry(18, 28, 1), 71 new THREE.MeshStandardMaterial({ color: 0x444444, side: THREE.DoubleSide }) 72 ); 73 doorWallTop.position.set(0, 34, 0); 74 scene.add(doorWallTop); 75 76 const doorWallLeft = new THREE.Mesh( 77 new THREE.BoxGeometry(4, 20, 1), 78 new THREE.MeshStandardMaterial({ color: 0x444444, side: THREE.DoubleSide }) 79 ); 80 doorWallLeft.position.set(8, 10, 0); 81 scene.add(doorWallLeft); 82 83 const doorWallRight = new THREE.Mesh( 84 new THREE.BoxGeometry(4, 20, 1), 85 new THREE.MeshStandardMaterial({ color: 0x444444, side: THREE.DoubleSide }) 86 ); 87 doorWallRight.position.set(-8, 10, 0); 88 scene.add(doorWallRight); 89 90 // --- 扉の作成(蝶番を軸に開くようにGroupを使用) --- 91 const leftDoorPivot = new THREE.Group(); 92 leftDoorPivot.position.set(6, 10, 0); 93 const leftDoor = new THREE.Mesh( 94 new THREE.BoxGeometry(6, 20, 0.5), 95 new THREE.MeshStandardMaterial({ color: 0x5a3a22 }) 96 ); 97 leftDoor.position.set(-3, 0, 0); 98 leftDoorPivot.add(leftDoor); 99 scene.add(leftDoorPivot); 100 101 const rightDoorPivot = new THREE.Group(); 102 rightDoorPivot.position.set(-6, 10, 0); 103 const rightDoor = new THREE.Mesh( 104 new THREE.BoxGeometry(6, 20, 0.5), 105 new THREE.MeshStandardMaterial({ color: 0x223a5a }) 106 ); 107 rightDoor.position.set(3, 0, 0); 108 rightDoorPivot.add(rightDoor); 109 scene.add(rightDoorPivot); 110 111 // --- 光源 --- 112 const light = new THREE.DirectionalLight(0xffffff, 3); 113 light.position.set(0, 6, 48); 114 scene.add(light); 115 116 const ambientLight = new THREE.AmbientLight(0xffffff, 0.3); 117 scene.add(ambientLight); 118 119 // --- カメラ --- 120 camera.position.set(-7, 6, 20); 121 camera.lookAt(0, 8, 0); 122 123 // --- クリック判定とアニメーション状態 --- 124 const raycaster = new THREE.Raycaster(); 125 const mouse = new THREE.Vector2(); 126 let isOpen = false; 127 128 function onClick(event: MouseEvent) { 129 const rect = renderer.domElement.getBoundingClientRect(); 130 mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; 131 mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; 132 133 raycaster.setFromCamera(mouse, camera); 134 const intersects = raycaster.intersectObjects([leftDoor, rightDoor]); 135 136 if (intersects.length > 0) { 137 isOpen = !isOpen; 138 } 139 } 140 141 renderer.domElement.addEventListener("click", onClick); 142 143 // --- アニメーションループ --- 144 let animationFrameId: number; 145 146 function animate() { 147 animationFrameId = requestAnimationFrame(animate); 148 149 const targetLeftRotation = isOpen ? -Math.PI / 2 : 0; 150 const targetRightRotation = isOpen ? Math.PI / 2 : 0; 151 152 leftDoorPivot.rotation.y += (targetLeftRotation - leftDoorPivot.rotation.y) * 0.1; 153 rightDoorPivot.rotation.y += (targetRightRotation - rightDoorPivot.rotation.y) * 0.1; 154 155 renderer.render(scene, camera); 156 } 157 158 animate(); 159 160 // --- クリーンアップ --- 161 return () => { 162 cancelAnimationFrame(animationFrameId); 163 renderer.domElement.removeEventListener("click", onClick); 164 renderer.dispose(); 165 }; 166 }, []); 167 168 return ( 169 <div 170 ref={mountRef} 171 style={{ 172 width: "100vw", 173 height: "100vh", 174 overflow: "hidden", 175 }} 176 /> 177 ); 178} 179

投稿2026/11/19 21:20

sgrgrgrgr

総合スコア1

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.25%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問