<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Babylon.js VR (WebXR) Scene</title>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script src="https://preview.babylonjs.com/babylon.js"></script>
<script>
const canvas = document.getElementById("renderCanvas");
const engine = new BABYLON.Engine(canvas, true);
const createScene = async function () {
const scene = new BABYLON.Scene(engine);
// カメラとライトはVRモードでは自動で設定されることが多いが、
// PCでの閲覧用に設定しておく
const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 10, new BABYLON.Vector3(0, 0, 0), scene);
camera.attachControl(canvas, true);
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0), scene);
// シーンにオブジェクトを追加
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: 1}, scene);
sphere.position.y = 1.5;
// 周りに箱をいくつか配置
for(let i = 0; i < 6; i++) {
const box = BABYLON.MeshBuilder.CreateBox("box" + i, {size: 0.5}, scene);
box.position.x = Math.sin(i * Math.PI / 3) * 3;
box.position.z = Math.cos(i * Math.PI / 3) * 3;
box.position.y = 0.25;
}
// 地面を作成
const ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 15, height: 15}, scene);
// --- ここからがVR対応のコード ---
// WebXRヘルパーを使ってVR体験を非同期で作成
const xr = await scene.createDefaultXRExperienceAsync({
// テレポート可能な床のメッシュを指定
floorMeshes: [ground],
});
return scene;
};
// シーンを作成して実行
createScene().then(scene => {
engine.runRenderLoop(function () {
if (scene) {
scene.render();
}
});
});
window.addEventListener("resize", function () {
engine.resize();
});
</script>
</body>
</html>
使用変数
-------( Function ) | |
box | |
camera | |
canvas | |
charset | |
createScene | |
engine | |
ground | |
i | |
id | |
light | |
scene | |
sphere | |
src | |
x | |
xr | |
y | |
z |