コードをメモ帳などのテキストエディタに貼り付け、ファイル名を「index.html」として保存します。その後、保存したファイルをブラウザで開けば、コードが実行されます。
恐怖ホラーゲーム。球の中に閉じ込められてしまうゲーム。
カーソルキーで操作です。
参考文献。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>360度パノラマビュー</title>
<style>
body { margin: 0; } /* ページの余白をなくす */
canvas { display: block; } /* キャンバスの表示設定 */
</style>
</head>
<body>
<!-- Three.js ライブラリの読み込み -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
// グローバル変数宣言
let camera, scene, renderer, sphere; // カメラ、シーン、レンダラー、球体オブジェクト
let videoTexture; // Webカメラの映像をテクスチャにするための変数
const rotationSpeed = 0.02; // 球体の回転速度
// 初期化関数
function init() {
// シーンの作成
scene = new THREE.Scene();
// レンダラーの作成とサイズ設定
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement); // レンダラーのDOM要素をページに追加
// カメラを作成し、球体の中心に配置
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 0); // カメラの位置を球体の中心にセット
// Webカメラの映像を取得
const video = document.createElement('video'); // video要素を作成
navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
video.srcObject = stream; // Webカメラのストリームを設定
video.play(); // 映像再生
// Webカメラ映像をテクスチャに変換
videoTexture = new THREE.VideoTexture(video);
// 球体のジオメトリ(半径5、分割数32)
const geometry = new THREE.SphereGeometry(5, 32, 32);
// テクスチャを適用したマテリアルを作成し、内側が見えるようにDoubleSide設定
const material = new THREE.MeshBasicMaterial({ map: videoTexture, side: THREE.BackSide });
// 球体メッシュの作成
sphere = new THREE.Mesh(geometry, material);
scene.add(sphere); // シーンに球体を追加
// アニメーション開始
animate();
});
// ウィンドウサイズ変更時にカメラとレンダラーの調整
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight); // レンダラーサイズ更新
camera.aspect = window.innerWidth / window.innerHeight; // カメラのアスペクト比更新
camera.updateProjectionMatrix(); // カメラの投影行列更新
});
// キーボード入力で球体の回転を制御
window.addEventListener('keydown', (event) => {
if (event.key === 'ArrowLeft') {
sphere.rotation.y += rotationSpeed; // 左キーで球体のY軸回転を増加
} else if (event.key === 'ArrowRight') {
sphere.rotation.y -= rotationSpeed; // 右キーで球体のY軸回転を減少
} else if (event.key === 'ArrowUp') {
sphere.rotation.x += rotationSpeed; // 上キーで球体のX軸回転を増加
} else if (event.key === 'ArrowDown') {
sphere.rotation.x -= rotationSpeed; // 下キーで球体のX軸回転を減少
}
});
}
// アニメーションループ
function animate() {
requestAnimationFrame(animate); // フレームごとの再描画リクエスト
// シーンをカメラの視点でレンダリング
renderer.render(scene, camera);
}
// 初期化関数の実行
init();
</script>
</body>
</html>