<!DOCTYPE html>
<!-- PCクレジット追加 -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Babylon Template with VR Joystick Movement & UI (Config Optimized)</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" touch-action="none"></canvas>
<script src="https://cdn.babylonjs.com/v8.31.0/babylon.js"></script>
<script src="https://cdn.babylonjs.com/v8.31.0/gui/babylon.gui.min.js"></script>
<script src="https://cdn.babylonjs.com/v8.31.0/havok/HavokPhysics_umd.js"></script>
<script src="https://www.unpkg.com/babylon-mmd@1.0.0/umd/babylon.mmd.min.js"></script>
<script src="https://code.jquery.com/pep/0.4.3/pep.js"></script>
<script>
const canvas = document.getElementById("renderCanvas"); // Get the canvas element
const engine = new BABYLON.Engine(canvas, true); // Generate the BABYLON 3D engine
// ★★★ 設定項目ここから ★★★
// --------------------------------------------------------------------------------
// 1. パス設定
// --------------------------------------------------------------------------------
const assetsPath = 'assets/';
const motionFolder = assetsPath + 'SummerIdol2020REMAKE/';
// --------------------------------------------------------------------------------
// 2. モデル1 (Rin) の設定
// --------------------------------------------------------------------------------
const MODEL_1_PATH = assetsPath + 'mmd/YYBrin/';
const MODEL_1_PMX = MODEL_1_PATH + 'YYB Kagamine Rin_10th_v1.0.pmx';
const MODEL_1_VMD = motionFolder + 'mmd_SummerIdol_RIN.vmd';
const MODEL_1_OFFSET_X = -1.0; // X軸オフセット (左端へ2.0m)
const MODEL_1_OFFSET_Z = 0.0; // Z軸オフセット
const IS_MODEL_1_VISIBLE = true; // モデル1の表示 (true: ON, false: OFF)
// --------------------------------------------------------------------------------
// 3. モデル2 (Miku) の設定
// --------------------------------------------------------------------------------
const MODEL_2_PATH = assetsPath + 'mmd/pumiku/';
const MODEL_2_PMX = MODEL_2_PATH + 'pumiku.pmx';
const MODEL_2_VMD = motionFolder + 'mmd_SummerIdol_MIK.vmd';
const MODEL_2_OFFSET_X = 1.0; // X軸オフセット (中央)
const MODEL_2_OFFSET_Z = 0.0; // Z軸オフセット
const IS_MODEL_2_VISIBLE = true; // モデル2の表示 (true: ON, false: OFF)
// --------------------------------------------------------------------------------
// 4. モデル3 (Teto) の設定 ★新規追加★
// --------------------------------------------------------------------------------
const MODEL_3_PATH = assetsPath + 'mmd/hanamiku/';
const MODEL_3_PMX = MODEL_3_PATH + 'hanamiku.pmx';
const MODEL_3_VMD = motionFolder + 'mmd_SummerIdol_RIN.vmd';
const MODEL_3_OFFSET_X = 5.0; // X軸オフセット (右端へ2.0m)
const MODEL_3_OFFSET_Z = 18.0; // Z軸オフセット
const IS_MODEL_3_VISIBLE = true; // モデル3の表示 (true: ON, false: OFF)
// --------------------------------------------------------------------------------
// 5. モーション・オーディオ・カメラの設定 (3体共通)
// --------------------------------------------------------------------------------
const AUDIO_WAV = motionFolder + 'pv_624.wav';
const CAMERA_VMD = motionFolder + 'Camera_MAIN.vmd';
// --------------------------------------------------------------------------------
// 6. ステージの設定
// --------------------------------------------------------------------------------
const STAGE_PATH = assetsPath + 'stage/taikukan/';
const STAGE_PMX = STAGE_PATH + 'taikukan.pmx';
// ステージの座標調整 (ステージを中央の原点から移動・回転させる場合に使う)
const STAGE_POSITION_Y = 0; // Y軸位置 (例: -1.0 で1m沈ませる)
const STAGE_SCALE = 1.0; // 拡大率 (例: 1.2 で1.2倍に)
const STAGE_ROTATION_Y = 0; // Y軸回転 (ラジアン, 例: Math.PI / 2 で90度回転)
const IS_STAGE_VISIBLE = true; // ステージの表示 (true: ON, false: OFF)
// --------------------------------------------------------------------------------
// 7. VRカメラの初期設定
// --------------------------------------------------------------------------------
const VR_FRONT_CAMERA_POS = new BABYLON.Vector3(0, 16, -20); // 正面ボタンのカメラ位置
const VR_FRONT_CAMERA_TARGET = new BABYLON.Vector3(0, 10, 0); // 正面ボタンのカメラ視線目標
const VR_BACK_CAMERA_POS = new BABYLON.Vector3(0, 16, 20); // 背面ボタンのカメラ位置
// --------------------------------------------------------------------------------
// 8. 初期動作設定
// --------------------------------------------------------------------------------
let isLooping = false; // アニメーションの初期リピート設定
// --------------------------------------------------------------------------------
// ★★★ 設定項目ここまで ★★★
// Add your code here matching the playground format
const createScene = async function (engine) {
const scene = new BABYLON.Scene(engine);
let adt; // VRコントローラー用GUI
let coordinateTextBlock;
let mmdModel_1 = null;
let mmdModel_2 = null;
let mmdModel_3 = null;
let mmdMesh_2 = null;
let mmdMesh_3 = null;
let modelMotion_2 = null;
let modelMotion_3 = null;
let latestBonePosition_1 = new BABYLON.Vector3(0, 0, 0);
let latestBonePosition_2 = new BABYLON.Vector3(0, 0, 0);
let latestBonePosition_3 = new BABYLON.Vector3(0, 0, 0);
// ★追加★ PC用オーバーレイGUIとクレジット表示用テキスト
let adtUI;
let creditsTextBlock;
const camera = new BABYLONMMD.MmdCamera("mmdCamera", new BABYLON.Vector3(0, 10, 0), scene);
// スカイボックス/グラウンドの代わりにステージを使用するため、デフォルトの地面を作成
const ground = BABYLON.MeshBuilder.CreateGround("Ground", { width: 200, height: 200, subdivisions: 2, updatable: false }, scene);
ground.receiveShadows = true;
const hemisphericLight = new BABYLON.HemisphericLight("HemisphericLight", new BABYLON.Vector3(0, 10, -10), scene);
hemisphericLight.intensity = 0.3;
hemisphericLight.specular = new BABYLON.Color3(0, 0, 0);
hemisphericLight.groundColor = new BABYLON.Color3(1.1, 1.1, 1.1);
const shadowLight = new BABYLON.DirectionalLight("shadowLight", new BABYLON.Vector3(-1, -2, 1), scene);
shadowLight.position = new BABYLON.Vector3(20, 100, 100);
const shadowGenerator = new BABYLON.ShadowGenerator(1024, shadowLight, true);
shadowGenerator.useBlurExponentialShadowMap = true;
shadowGenerator.blurKernel = 32;
// --- ステージのメッシュを読み込む ---
let stageMesh = null;
if (IS_STAGE_VISIBLE) {
stageMesh = await BABYLON.SceneLoader.ImportMeshAsync(undefined, STAGE_PMX, undefined, scene).then((result) => result.meshes[0]);
// ★★★ 設定項目反映: ステージの位置と大きさを調整 ★★★
stageMesh.position.y = STAGE_POSITION_Y;
stageMesh.scaling = new BABYLON.Vector3(STAGE_SCALE, STAGE_SCALE, STAGE_SCALE);
stageMesh.rotation.y = STAGE_ROTATION_Y;
stageMesh.isVisible = IS_STAGE_VISIBLE;
// ★★★ 設定項目反映ここまで ★★★
// 地面と影の調整
stageMesh.getChildMeshes().forEach(mesh => mesh.receiveShadows = true);
ground.dispose(); // 元の地面を削除
}
const vmdLoader = new BABYLONMMD.VmdLoader(scene);
// --- モデル1 (Rin) のメッシュを読み込む ---
let mmdMesh_1 = null;
if (IS_MODEL_1_VISIBLE) {
mmdMesh_1 = await BABYLON.SceneLoader.ImportMeshAsync(undefined, MODEL_1_PMX, undefined, scene).then((result) => result.meshes[0]);
shadowGenerator.addShadowCaster(mmdMesh_1);
mmdMesh_1.receiveShadows = true;
mmdMesh_1.position.x = MODEL_1_OFFSET_X;
mmdMesh_1.position.z = MODEL_1_OFFSET_Z;
mmdMesh_1.isVisible = IS_MODEL_1_VISIBLE;
}
// --- モデル2 (Miku) のメッシュを読み込む ---
if (IS_MODEL_2_VISIBLE) {
mmdMesh_2 = await BABYLON.SceneLoader.ImportMeshAsync(undefined, MODEL_2_PMX, undefined, scene).then((result) => result.meshes[0]);
shadowGenerator.addShadowCaster(mmdMesh_2);
mmdMesh_2.receiveShadows = true;
mmdMesh_2.position.x = MODEL_2_OFFSET_X;
mmdMesh_2.position.z = MODEL_2_OFFSET_Z;
mmdMesh_2.isVisible = IS_MODEL_2_VISIBLE;
}
// --- モデル3 (Teto) のメッシュを読み込む ---
if (IS_MODEL_3_VISIBLE) {
mmdMesh_3 = await BABYLON.SceneLoader.ImportMeshAsync(undefined, MODEL_3_PMX, undefined, scene).then((result) => result.meshes[0]);
shadowGenerator.addShadowCaster(mmdMesh_3);
mmdMesh_3.receiveShadows = true;
mmdMesh_3.position.x = MODEL_3_OFFSET_X;
mmdMesh_3.position.z = MODEL_3_OFFSET_Z;
mmdMesh_3.isVisible = IS_MODEL_3_VISIBLE;
}
// モーションのロード
const modelMotion_1 = IS_MODEL_1_VISIBLE ? await vmdLoader.loadAsync("model_motion_1", MODEL_1_VMD) : null;
modelMotion_2 = IS_MODEL_2_VISIBLE ? await vmdLoader.loadAsync("model_motion_2", MODEL_2_VMD) : null;
modelMotion_3 = IS_MODEL_3_VISIBLE ? await vmdLoader.loadAsync("model_motion_3", MODEL_3_VMD) : null;
const cameraMotion = await vmdLoader.loadAsync("camera_motion", CAMERA_VMD);
const havokInstance = await HavokPhysics();
const havokPlugin = new BABYLON.HavokPlugin(true, havokInstance);
scene.enablePhysics(new BABYLON.Vector3(0, -9.8 * 8, 0), havokPlugin);
const mmdRuntime = new BABYLONMMD.MmdRuntime(scene, new BABYLONMMD.MmdPhysics(scene));
mmdRuntime.register(scene);
// モデル1にモーションを適用
if (IS_MODEL_1_VISIBLE && mmdMesh_1) {
mmdModel_1 = mmdRuntime.createMmdModel(mmdMesh_1);
const modelAnimationHandle = mmdModel_1.createRuntimeAnimation(modelMotion_1);
mmdModel_1.setRuntimeAnimation(modelAnimationHandle);
}
// モデル2にモーションを適用
if (IS_MODEL_2_VISIBLE && mmdMesh_2) {
mmdModel_2 = mmdRuntime.createMmdModel(mmdMesh_2);
const modelAnimationHandle_2 = mmdModel_2.createRuntimeAnimation(modelMotion_2);
mmdModel_2.setRuntimeAnimation(modelAnimationHandle_2);
}
// モデル3にモーションを適用
if (IS_MODEL_3_VISIBLE && mmdMesh_3) {
mmdModel_3 = mmdRuntime.createMmdModel(mmdMesh_3);
const modelAnimationHandle_3 = mmdModel_3.createRuntimeAnimation(modelMotion_3);
mmdModel_3.setRuntimeAnimation(modelAnimationHandle_3);
}
// カメラにモーションを適用
mmdRuntime.addAnimatable(camera);
const cameraMotionHandle = camera.createRuntimeAnimation(cameraMotion);
camera.setRuntimeAnimation(cameraMotionHandle);
// オーディオと再生
const audioPlayer = new BABYLONMMD.StreamAudioPlayer(scene);
audioPlayer.preservesPitch = false;
audioPlayer.source = AUDIO_WAV;
// ★追加★ 音量を1 (100%)、ミュートを解除 (false) に設定
audioPlayer.volume = 1;
audioPlayer.muted = false;
mmdRuntime.setAudioPlayer(audioPlayer);
mmdRuntime.playAnimation();
const mmdPlayerControl = new BABYLONMMD.MmdPlayerControl(scene, mmdRuntime, audioPlayer);
mmdPlayerControl.showPlayerControl();
// ★★★ 追加: PC用 クレジット表示UI (ここから) ★★★
// =================================================================
// PC用 クレジット表示UI
// =================================================================
adtUI = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
// ★★★ クレジットテキストの内容 (↓ここを書き換えてください↓) ★★★
const creditTextContent =
"曲: 楽曲名 (作曲者名)\n" +
"モデル: モデル1, モデル2, モデル3 (制作者名)\n" +
"モーション: モーション名 (制作者名)\n" +
"ステージ: ステージ名 (制作者名)";
// ★★★ クレジットテキストの内容 (↑ここまで↑) ★★★
creditsTextBlock = new BABYLON.GUI.TextBlock("creditsText", creditTextContent);
creditsTextBlock.color = "white";
creditsTextBlock.fontSize = 20;
creditsTextBlock.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; // 右寄せ
creditsTextBlock.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM; // 下寄せ
creditsTextBlock.paddingRight = "20px"; // 右からのパディング
creditsTextBlock.paddingBottom = "20px"; // 下からのパディング
creditsTextBlock.shadowColor = "black"; // 影の色
creditsTextBlock.shadowBlur = 2;
creditsTextBlock.shadowOffsetX = 1;
creditsTextBlock.shadowOffsetY = 1;
// 全画面UIの右下に配置
creditsTextBlock.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM;
creditsTextBlock.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT;
creditsTextBlock.isVisible = false; // 初期状態は非表示
adtUI.addControl(creditsTextBlock);
// ★★★ 追加: PC用 クレジット表示UI (ここまで) ★★★
// --- モデル1のボーン座標を取得 ---
scene.onAfterPhysicsObservable.add(() => {
try {
if (mmdModel_1 && mmdModel_1.skeleton && IS_MODEL_1_VISIBLE) {
const targetBone = mmdModel_1.skeleton.bones.find(b => b.name === '上半身');
if (targetBone) {
finalMatrix.decompose(undefined, undefined, latestBonePosition_1);
}
}
} catch (e) {
// console.error("onAfterPhysicsObservable (Model 1) でエラー:", e);
}
});
// --- モデル2のボーン座標を取得 ---
scene.onAfterPhysicsObservable.add(() => {
try {
if (mmdModel_2 && mmdModel_2.skeleton && IS_MODEL_2_VISIBLE) {
const targetBone = mmdModel_2.skeleton.bones.find(b => b.name === '上半身');
if (targetBone) {
const finalMatrix = targetBone.getFinalMatrix();
finalMatrix.decompose(undefined, undefined, latestBonePosition_2);
}
}
} catch (e) {
// console.error("onAfterPhysicsObservable (Model 2) でエラー:", e);
}
});
// --- モデル3のボーン座標を取得 ---
scene.onAfterPhysicsObservable.add(() => {
try {
if (mmdModel_3 && mmdModel_3.skeleton && IS_MODEL_3_VISIBLE) {
const targetBone = mmdModel_3.skeleton.bones.find(b => b.name === '上半身');
if (targetBone) {
const finalMatrix = targetBone.getFinalMatrix();
finalMatrix.decompose(undefined, undefined, latestBonePosition_3);
}
}
} catch (e) {
// console.error("onAfterPhysicsObservable (Model 3) でエラー:", e);
}
});
// =================================================================
// VR機能、UIパネル、ジョイスティック移動処理
// =================================================================
const xr = await scene.createDefaultXRExperienceAsync({
uiOptions: {
sessionMode: 'immersive-vr',
supportedSessionModes: ['immersive-vr', 'immersive-ar']
}
});
let followingModelIndex = 0;
let followOffset = new BABYLON.Vector3();
// --- 左手コントローラーにUIパネルを追加 ---
xr.input.onControllerAddedObservable.add((controller) => {
if (controller.inputSource.handedness === 'left') {
let uiParent = scene.getTransformNodeByName("leftUIParent");
if (!uiParent) {
let followButton_1, followButton_2, followButton_3;
const buttonHeight = "60px";
const updateFollowButtonStyles = () => {
const defaultColor = "#607D8B"; // 追従
const activeColor = "#9C27B0"; // 解除
if (followButton_1) {
followButton_1.textBlock.text = (followingModelIndex === 1) ? "解除 1 (Rin)" : "追従 1 (Rin)";
followButton_1.background = (followingModelIndex === 1) ? activeColor : defaultColor;
}
if (followButton_2) {
followButton_2.textBlock.text = (followingModelIndex === 2) ? "解除 2 (Miku)" : "追従 2 (Miku)";
followButton_2.background = (followingModelIndex === 2) ? activeColor : defaultColor;
}
if (followButton_3) {
followButton_3.textBlock.text = (followingModelIndex === 3) ? "解除 3 (Teto)" : "追従 3 (Teto)";
followButton_3.background = (followingModelIndex === 3) ? activeColor : defaultColor;
}
};
uiParent = new BABYLON.TransformNode("leftUIParent", scene);
uiParent.position = new BABYLON.Vector3(0, 0.05, 0.08);
uiParent.rotation = new BABYLON.Vector3(Math.PI / 4, 0, 0);
const uiPlane = BABYLON.MeshBuilder.CreatePlane("uiPlane", { width: 0.25, height: 0.8 }, scene);
uiPlane.parent = uiParent;
uiPlane.visibility = 0.9;
adt = BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(uiPlane);
const stackPanel = new BABYLON.GUI.StackPanel();
stackPanel.isVertical = true;
stackPanel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
adt.addControl(stackPanel);
// 5. 「最初から」ボタン
const resetButton = BABYLON.GUI.Button.CreateSimpleButton("resetButton", "最初から");
resetButton.width = "100%"; resetButton.height = buttonHeight; resetButton.color = "white";
resetButton.background = "#4CAF50"; resetButton.fontSize = 24;
resetButton.onPointerClickObservable.add(() => {
mmdRuntime.seekAnimation(0);
});
stackPanel.addControl(resetButton);
// 6. 「再生/停止」トグルボタン
const playPauseButton = BABYLON.GUI.Button.CreateSimpleButton("playPauseButton", "停止");
playPauseButton.width = "100%"; playPauseButton.height = buttonHeight; playPauseButton.color = "white";
playPauseButton.background = "#f44336"; playPauseButton.fontSize = 24;
playPauseButton.onPointerClickObservable.add(() => {
if (mmdRuntime.isAnimationPlaying) {
mmdRuntime.pauseAnimation();
playPauseButton.textBlock.text = "再生";
playPauseButton.background = "#2196F3";
} else {
mmdRuntime.playAnimation();
playPauseButton.textBlock.text = "停止";
playPauseButton.background = "#f44336";
}
});
stackPanel.addControl(playPauseButton);
// 7. 「正面」ボタン
const frontButton = BABYLON.GUI.Button.CreateSimpleButton("frontButton", "正面");
frontButton.width = "100%"; frontButton.height = buttonHeight; frontButton.color = "white";
frontButton.background = "#2196F3"; frontButton.fontSize = 24;
frontButton.onPointerClickObservable.add(() => {
followingModelIndex = 0;
updateFollowButtonStyles();
xr.baseExperience.camera.position.copyFrom(VR_FRONT_CAMERA_POS);
xr.baseExperience.camera.setTarget(VR_FRONT_CAMERA_TARGET);
});
stackPanel.addControl(frontButton);
// 8. 「背面」ボタン
const backButton = BABYLON.GUI.Button.CreateSimpleButton("backButton", "背面");
backButton.width = "100%"; backButton.height = buttonHeight; backButton.color = "white";
backButton.background = "#FF9800"; backButton.fontSize = 24;
backButton.onPointerClickObservable.add(() => {
followingModelIndex = 0;
updateFollowButtonStyles();
xr.baseExperience.camera.position.copyFrom(VR_BACK_CAMERA_POS);
xr.baseExperience.camera.setTarget(VR_FRONT_CAMERA_TARGET);
});
stackPanel.addControl(backButton);
// 9. 「リピート」トグルボタン
const repeatButton = BABYLON.GUI.Button.CreateSimpleButton("repeatButton", isLooping ? "リピート: オン" : "リピート: オフ");
repeatButton.width = "100%"; repeatButton.height = buttonHeight; repeatButton.color = "white";
repeatButton.background = isLooping ? "#FFC107" : "#795548";
repeatButton.fontSize = 24;
repeatButton.onPointerClickObservable.add(() => {
isLooping = !isLooping;
if (isLooping) {
repeatButton.textBlock.text = "リピート: オン";
repeatButton.background = "#FFC107";
} else {
repeatButton.textBlock.text = "リピート: オフ";
repeatButton.background = "#795548";
}
});
stackPanel.addControl(repeatButton);
// 10. 「ARモード」ボタン
const arButton = BABYLON.GUI.Button.CreateSimpleButton("arButton", "ARモード");
arButton.width = "100%"; arButton.height = buttonHeight; arButton.color = "white";
arButton.background = "#9C27B0"; arButton.fontSize = 24;
arButton.onPointerClickObservable.add(async () => {
if (xr.baseExperience.state === BABYLON.WebXRState.IN_XR) {
await xr.baseExperience.exitXRAsync();
}
await xr.baseExperience.enterXRAsync("immersive-ar", "local-floor");
});
stackPanel.addControl(arButton);
// 11. 「追従 1 (Rin)」ボタン
followButton_1 = BABYLON.GUI.Button.CreateSimpleButton("followButton1", "追従 1 (Rin)");
followButton_1.width = "100%"; followButton_1.height = buttonHeight; followButton_1.color = "white";
followButton_1.fontSize = 24;
followButton_1.onPointerClickObservable.add(() => {
if (followingModelIndex === 1) {
followingModelIndex = 0;
} else {
followingModelIndex = 1;
const xrCamera = xr.baseExperience.camera;
followOffset = xrCamera.position.subtract(latestBonePosition_1);
}
updateFollowButtonStyles();
});
if (!IS_MODEL_1_VISIBLE || !mmdModel_1) {
followButton_1.textBlock.text = "モデル1非表示";
followButton_1.background = "#D3D3D3";
followButton_1.isHitTestVisible = false;
}
stackPanel.addControl(followButton_1);
// 12. 「追従 2 (Miku)」ボタン
followButton_2 = BABYLON.GUI.Button.CreateSimpleButton("followButton2", "追従 2 (Miku)");
followButton_2.width = "100%"; followButton_2.height = buttonHeight; followButton_2.color = "white";
followButton_2.fontSize = 24;
followButton_2.onPointerClickObservable.add(() => {
if (followingModelIndex === 2) {
followingModelIndex = 0;
} else {
followingModelIndex = 2;
const xrCamera = xr.baseExperience.camera;
followOffset = xrCamera.position.subtract(latestBonePosition_2);
}
updateFollowButtonStyles();
});
if (!IS_MODEL_2_VISIBLE || !mmdModel_2) {
followButton_2.textBlock.text = "モデル2非表示";
followButton_2.background = "#D3D3D3";
followButton_2.isHitTestVisible = false;
}
stackPanel.addControl(followButton_2);
// 13. 「追従 3 (Teto)」ボタン
followButton_3 = BABYLON.GUI.Button.CreateSimpleButton("followButton3", "追従 3 (Teto)");
followButton_3.width = "100%"; followButton_3.height = buttonHeight; followButton_3.color = "white";
followButton_3.fontSize = 24;
followButton_3.onPointerClickObservable.add(() => {
if (followingModelIndex === 3) {
followingModelIndex = 0;
} else {
followingModelIndex = 3;
const xrCamera = xr.baseExperience.camera;
followOffset = xrCamera.position.subtract(latestBonePosition_3);
}
updateFollowButtonStyles();
});
if (!IS_MODEL_3_VISIBLE || !mmdModel_3) {
followButton_3.textBlock.text = "モデル3非表示";
followButton_3.background = "#D3D3D3";
followButton_3.isHitTestVisible = false;
}
stackPanel.addControl(followButton_3);
updateFollowButtonStyles();
// 座標表示用のテキストブロック
coordinateTextBlock = new BABYLON.GUI.TextBlock("coordinateTextBlock");
coordinateTextBlock.text = "Y | 1: 0.00 | 2: 0.00 | 3: 0.00";
coordinateTextBlock.color = "white";
coordinateTextBlock.fontSize = 20;
coordinateTextBlock.height = "50px";
stackPanel.addControl(coordinateTextBlock);
// ボーン名表示ボタンとテキストブロック (デバッグ用)
const showBonesButton = BABYLON.GUI.Button.CreateSimpleButton("showBonesButton", "ボーン名表示(M1)");
showBonesButton.width = "100%"; showBonesButton.height = buttonHeight; showBonesButton.color = "white";
showBonesButton.background = "#3F51B5"; showBonesButton.fontSize = 24;
stackPanel.addControl(showBonesButton);
const boneListTextBlock = new BABYLON.GUI.TextBlock("boneListTextBlock", "↑ボタンを押してボーン名を表示");
boneListTextBlock.color = "white"; boneListTextBlock.fontSize = 16;
boneListTextBlock.textWrapping = true;
boneListTextBlock.resizeToFit = true;
boneListTextBlock.paddingTop = "10px";
stackPanel.addControl(boneListTextBlock);
showBonesButton.onPointerClickObservable.add(() => {
let debugMessage = "";
if (mmdModel_1 && mmdModel_1.skeleton) {
const bones = mmdModel_1.skeleton.bones;
const boneCount = bones.length;
debugMessage += `ボーンの数: ${boneCount}個\n`;
if (boneCount > 0) {
const boneNames = bones.slice(0, 15).map(bone => bone.name).join(', ') + (boneCount > 15 ? ', ...' : '');
debugMessage += "名前リスト: " + boneNames;
} else {
debugMessage += "ボーン配列は空です。";
}
} else if (mmdModel_1) {
debugMessage = "モデルはありますが、スケルトンが見つかりません。";
} else {
debugMessage = "MMDモデル自体が見つかりません。";
}
boneListTextBlock.text = debugMessage;
});
}
uiParent.parent = controller.grip;
}
});
// VRモード切替時のアニメーション制御
xr.baseExperience.onStateChangedObservable.add((state) => {
if (state === BABYLON.WebXRState.IN_XR) {
camera.setRuntimeAnimation(null);
if (adtUI) adtUI.rootContainer.isVisible = false; // ★追加★ PC用UIを非表示
if (xr.baseExperience.sessionManager.sessionMode === 'immersive-ar') {
ground.visibility = false;
if (stageMesh) {
stageMesh.isVisible = false;
stageMesh.getChildMeshes().forEach(mesh => {mesh.isVisible = false;});
}
}
} else if (state === BABYLON.WebXRState.NOT_IN_XR) {
camera.setRuntimeAnimation(cameraMotionHandle);
followingModelIndex = 0;
ground.visibility = true;
if (stageMesh) {
stageMesh.isVisible = IS_STAGE_VISIBLE;
stageMesh.getChildMeshes().forEach(mesh => {mesh.isVisible = IS_STAGE_VISIBLE;});
}
if (adtUI) adtUI.rootContainer.isVisible = true; // ★追加★ PC用UIを再表示
}
});
// 毎フレームごとの処理
scene.onBeforeRenderObservable.add(() => {
// 手動リピートロジック
if (isLooping && mmdRuntime.isAnimationPlaying) {
const currentTime = mmdRuntime.currentTime;
const duration = mmdRuntime.animationDuration;
if (duration > 0 && currentTime >= duration * 0.999) {
mmdRuntime.seekAnimation(0);
mmdRuntime.playAnimation();
}
}
// ★★★ 追加: クレジット表示タイミング制御 ★★★
// VRモードでない場合(PCモード)のみ処理
if (mmdRuntime && creditsTextBlock && xr.baseExperience.state === BABYLON.WebXRState.NOT_IN_XR) {
const currentTime = mmdRuntime.currentTime;
const duration = mmdRuntime.animationDuration;
if (duration > 0) {
const triggerTime = duration * 0.9;
// 9/10 ~ 10/10 の間だけ表示
if (currentTime >= triggerTime && currentTime <= duration) {
creditsTextBlock.isVisible = true;
} else {
creditsTextBlock.isVisible = false; // それ以外の時間は非表示
}
} else {
creditsTextBlock.isVisible = false;
}
} else if (creditsTextBlock) {
// VR中、またはMMDランタイムが存在しない場合は非表示
creditsTextBlock.isVisible = false;
}
// ★★★ 追加ここまで ★★★
// --- これ以降はVRモード中の処理 ---
if (xr.baseExperience.state !== BABYLON.WebXRState.IN_XR) return;
// ボーン座標をUIに表示 (3モデルのY座標)
if (coordinateTextBlock) {
coordinateTextBlock.text = `Y | 1: ${latestBonePosition_1.y.toFixed(2)} | 2: ${latestBonePosition_2.y.toFixed(2)} | 3: ${latestBonePosition_3.y.toFixed(2)}`;
}
// --- 追従モードの処理 ---
if (followingModelIndex > 0) {
let targetPosition = new BABYLON.Vector3();
if (followingModelIndex === 1) {
targetPosition.copyFrom(latestBonePosition_1);
} else if (followingModelIndex === 2) {
targetPosition.copyFrom(latestBonePosition_2);
} else if (followingModelIndex === 3) {
targetPosition.copyFrom(latestBonePosition_3);
}
const desiredPosition = targetPosition.clone().add(followOffset);
xr.baseExperience.camera.position.copyFrom(desiredPosition);
}
// --- ジョイスティック操作の処理 ---
if (followingModelIndex === 0) {
const deltaMillis = engine.getDeltaTime();
const xrCamera = xr.baseExperience.camera;
// 左コントローラー: 平行移動
const leftController = xr.input.controllers.find(c => c.inputSource.handedness === 'left');
if (leftController?.motionController) {
const thumbstick = leftController.motionController.getComponent("xr-standard-thumbstick");
if (thumbstick?.axes) {
const moveSpeed = 6.0 * deltaMillis / 1000;
const forward = xrCamera.getDirection(BABYLON.Vector3.Forward());
forward.y = 0;
xrCamera.position.addInPlace(forward.normalize().scale(-thumbstick.axes.y * moveSpeed));
const right = xrCamera.getDirection(BABYLON.Vector3.Right());
xrCamera.position.addInPlace(right.scale(thumbstick.axes.x * moveSpeed));
}
}
// 右コントローラー: 回転と上下移動
const rightController = xr.input.controllers.find(c => c.inputSource.handedness === 'right');
if (rightController?.motionController) {
const thumbstick = rightController.motionController.getComponent("xr-standard-thumbstick");
if (thumbstick?.axes) {
const rotationThreshold = 0.2;
if (Math.abs(thumbstick.axes.x) > rotationThreshold) {
const rotSpeed = 0.4 * deltaMillis / 1000;
if (xrCamera.parent) {
xrCamera.parent.rotate(BABYLON.Vector3.Up(), thumbstick.axes.x * rotSpeed, BABYLON.Space.WORLD);
}
}
if (Math.abs(thumbstick.axes.y) > rotationThreshold) {
const verticalSpeed = 2.0 * deltaMillis / 1000;
xrCamera.position.y += -thumbstick.axes.y * verticalSpeed;
}
}
}
}
});
return scene;
};
(async function () {
// ★変更★ 物理演算の例外を握りつぶさないように try...catch を削除
canvas.focus();
const scene = await createScene(engine); //Call the createScene function
// Register a render loop to repeatedly render the scene
engine.runRenderLoop(async function () {
scene.render();
});
// Watch for browser/canvas resize events
window.addEventListener("resize", function () {
engine.resize();
});
})()
</script>
</body>
</html>
使用変数
| -------( Function ) | |
| action | |
| activeColor | |
| adt | |
| adtUI | |
| arButton | |
| assetsPath | |
| audioPlayer | |
| AUDIO_WAV | |
| b | |
| backButton | |
| background | |
| blurKernel | |
| bone | |
| boneCount | |
| boneListTextBlock | |
| boneNames | |
| bones | |
| br> // Register a render loop to repeatedly render the scene engine.runRenderLoop -------( Function ) | |
| buttonHeight | |
| c | |
| camera | |
| cameraMotion | |
| cameraMotionHandle | |
| CAMERA_VMD | |
| canvas | |
| charset | |
| color | |
| content | |
| createScene | |
| creditsTextBlock | |
| creditTextContent | |
| currentTime | |
| debugMessage | |
| defaultColor | |
| delAnimationHandle | |
| deltaMillis | |
| desiredPosition | |
| duration | |
| engine | |
| equiv | |
| finalMatrix | |
| FollowButtonStyles | |
| followButton_1 | |
| followButton_2 | |
| followButton_3 | |
| followOffset | |
| fontSize | |
| forward | |
| frontButton | |
| ground | |
| groundColor | |
| handedness | |
| havokInstance | |
| havokPlugin | |
| height | |
| hemisphericLight | |
| id | |
| intensity | |
| isHitTestVisible | |
| isLooping | |
| isVertical | |
| isVisible | |
| IS_MODEL_1_VISIBLE | |
| IS_MODEL_2_VISIBLE | |
| IS_MODEL_3_VISIBLE | |
| IS_STAGE_VISIBLE | |
| lAnimationHandle_2 | |
| lAnimationHandle_3 | |
| leftController | |
| mesh | |
| mmdMesh_1 | |
| mmdMesh_2 | |
| mmdMesh_3 | |
| mmdModel_1 | |
| mmdModel_2 | |
| mmdModel_3 | |
| mmdPlayerControl | |
| mmdRuntime | |
| modelMotion_1 | |
| modelMotion_2 | |
| modelMotion_3 | |
| MODEL_1_OFFSET_X | |
| MODEL_1_OFFSET_Z | |
| MODEL_1_PATH | |
| MODEL_1_PMX | |
| MODEL_1_VMD | |
| MODEL_2_OFFSET_X | |
| MODEL_2_OFFSET_Z | |
| MODEL_2_PATH | |
| MODEL_2_PMX | |
| MODEL_2_VMD | |
| MODEL_3_OFFSET_X | |
| MODEL_3_OFFSET_Z | |
| MODEL_3_PATH | |
| MODEL_3_PMX | |
| MODEL_3_VMD | |
| motionFolder | |
| moveSpeed | |
| muted | |
| name | |
| ollowingModelIndex | |
| oordinateTextBlock | |
| orizontalAlignment | |
| paddingBottom | |
| paddingRight | |
| paddingTop | |
| parent | |
| playPauseButton | |
| ponentialShadowMap | |
| position | |
| preservesPitch | |
| receiveShadows | |
| repeatButton | |
| resetButton | |
| resizeToFit | |
| right | |
| rightController | |
| RONT_CAMERA_TARGET | |
| rotation | |
| rotationThreshold | |
| rotSpeed | |
| R_FRONT_CAMERA_POS | |
| scaling | |
| scene | |
| sessionMode | |
| shadowBlur | |
| shadowColor | |
| shadowGenerator | |
| shadowLight | |
| shadowOffsetX | |
| shadowOffsetY | |
| showBonesButton | |
| source | |
| specular | |
| src | |
| stackPanel | |
| stageMesh | |
| STAGE_PATH | |
| STAGE_PMX | |
| STAGE_POSITION_Y | |
| STAGE_ROTATION_Y | |
| STAGE_SCALE | |
| state | |
| targetBone | |
| targetPosition | |
| testBonePosition_1 | |
| testBonePosition_2 | |
| testBonePosition_3 | |
| text | |
| textWrapping | |
| thumbstick | |
| triggerTime | |
| tVerticalAlignment | |
| uiParent | |
| uiPlane | |
| verticalAlignment | |
| verticalSpeed | |
| visibility | |
| vmdLoader | |
| volume | |
| VR_BACK_CAMERA_POS | |
| width | |
| x | |
| xmlns | |
| xr | |
| xrCamera | |
| y | |
| z |