🔬 AI発明ギャラリー › りい › アバターアスレチック
🔒 サンドボックス内で実行中 ⛶ 全画面で遊ぶ
HTML / CSS / JS
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>Roblox Pastel Obby Adventure</title>
  <!-- Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Lucide Icons -->
  <script src="https://unpkg.com/lucide@latest"></script>
  <!-- Three.js & OrbitControls -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600;700&family=M+PLUS+Rounded+1c:wght@400;700;900&display=swap');
    body {
      font-family: 'Fredoka', 'M PLUS Rounded 1c', sans-serif;
      user-select: none;
      -webkit-user-select: none;
      touch-action: manipulation;
      overflow: hidden;
    }
    .scrollbar-thin::-webkit-scrollbar {
      width: 5px;
      height: 5px;
    }
    .scrollbar-thin::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.3);
      border-radius: 9999px;
    }
    .roblox-glass {
      background: rgba(18, 20, 24, 0.78);
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
    }
    .press-effect:active {
      transform: scale(0.96);
    }
    /* Roblox風の十字カーソル(ShiftLock時) */
    .shift-lock-cursor {
      cursor: crosshair;
    }
  </style>
</head>
<body class="bg-slate-950 text-white w-screen h-screen relative select-none">

  <!-- ==========================================================
       1. ROBLOX フルスクリーンゲーム画面 (メインワールド)
       ========================================================== -->
  <div id="roblox-viewport" class="relative w-full h-full overflow-hidden">
    <canvas id="game-canvas" class="w-full h-full block"></canvas>

    <!-- ★ ROBLOX 公式風 トップバー (TopBar) ★ -->
    <header class="absolute top-0 left-0 right-0 h-12 roblox-glass border-b border-white/10 z-30 px-3 flex items-center justify-between pointer-events-auto">
      <!-- 左側: Robloxロゴメニュー・チャット・エモートボタン -->
      <div class="flex items-center gap-2 sm:gap-3">
        <!-- Roblox角型アイコン (クリックでESCゲーム内メニュー) -->
        <button onclick="toggleRobloxMenu()" class="w-9 h-9 rounded-lg bg-white/10 hover:bg-white/20 border border-white/15 flex items-center justify-center transition press-effect" title="Roblox Menu (Esc)">
          <div class="w-4 h-4 bg-white rotate-12 rounded-[2px] flex items-center justify-center shadow-inner">
            <div class="w-1.5 h-1.5 bg-slate-950 rotate-12 rounded-[1px]"></div>
          </div>
        </button>

        <!-- ゲーム切り替え (Discover) -->
        <button onclick="openGameDiscovery()" class="px-2.5 h-9 rounded-lg bg-white/10 hover:bg-white/20 border border-white/15 flex items-center gap-1.5 text-xs font-bold transition press-effect text-cyan-300" title="Games">
          <i data-lucide="compass" class="w-4 h-4"></i>
          <span class="hidden sm:inline">ゲーム一覧</span>
        </button>

        <!-- Roblox Studio モード切り替え -->
        <button onclick="toggleStudioMode()" class="px-2.5 h-9 rounded-lg bg-purple-600/50 hover:bg-purple-600/70 border border-purple-400/40 flex items-center gap-1.5 text-xs font-bold transition press-effect text-purple-200" title="Studio Mode">
          <i data-lucide="hammer" class="w-4 h-4"></i>
          <span id="studio-btn-label" class="hidden sm:inline">Studio (作成)</span>
        </button>

        <!-- チャット開閉ボタン -->
        <button onclick="toggleChatWindow()" class="w-9 h-9 rounded-lg bg-white/10 hover:bg-white/20 border border-white/15 flex items-center justify-center transition press-effect text-white/90" title="Chat (/)">
          <i data-lucide="message-square" class="w-4 h-4"></i>
        </button>

        <!-- エモートメニューボタン -->
        <button onclick="triggerEmote('dance')" class="px-2.5 h-9 rounded-lg bg-white/10 hover:bg-white/20 border border-white/15 flex items-center gap-1.5 text-xs font-bold transition press-effect text-pink-300" title="Emote (/e dance)">
          <i data-lucide="smile" class="w-4 h-4"></i>
          <span class="hidden sm:inline">ダンス</span>
        </button>

        <!-- アバターエディタ呼び出し -->
        <button onclick="openAvatarStudio()" class="px-3 h-9 rounded-lg bg-gradient-to-r from-pink-500 to-purple-600 hover:opacity-90 flex items-center gap-1.5 text-xs font-bold shadow-md transition press-effect text-white">
          <i data-lucide="shirt" class="w-3.5 h-3.5"></i>
          <span>アバター変更</span>
        </button>
      </div>

      <!-- 中央: ステージ進行インフォ & 特殊HUD -->
      <div class="flex items-center gap-2">
        <div class="hidden md:flex items-center gap-2 px-3 py-1 bg-white/5 rounded-full border border-white/10 text-xs">
          <span id="top-world-badge" class="text-pink-400 font-bold">🌸 Pastel Obby World</span>
          <span class="text-white/40">|</span>
          <span id="top-stage-txt" class="text-amber-300 font-bold">STAGE 1 / 6</span>
        </div>

        <!-- 溶岩サバイバル用 HUD -->
        <div id="lava-hud" class="hidden items-center gap-2 px-3 py-1 bg-rose-600/60 rounded-full border border-rose-400 text-xs font-black text-white animate-pulse">
          <i data-lucide="flame" class="w-3.5 h-3.5"></i>
          <span id="lava-timer">SURVIVE: 30s</span>
        </div>

        <!-- ペット&コイン用 HUD -->
        <div id="pet-hud" class="hidden items-center gap-2 px-3 py-1 bg-amber-500/30 rounded-full border border-amber-400 text-xs font-bold text-amber-300">
          <i data-lucide="coins" class="w-3.5 h-3.5 text-yellow-300"></i>
          <span id="pet-coin-count">0</span>
          <button onclick="openPetEggHatch()" class="ml-1 px-2 py-0.5 bg-yellow-400 hover:bg-yellow-300 text-slate-950 font-black rounded-md text-[10px]">
            たまご孵化 (10)
          </button>
        </div>
      </div>

      <!-- 右側: Leaderboard & 統計 (Roblox風) -->
      <div class="flex items-center gap-2">
        <div class="flex items-center gap-2 px-2.5 py-1 bg-black/40 rounded-lg border border-white/10 text-xs">
          <div class="flex items-center gap-1 text-amber-400 font-bold">
            <i data-lucide="star" class="w-3.5 h-3.5 fill-amber-400"></i>
            <span id="hud-stars">0</span>
          </div>
          <div class="w-[1px] h-3 bg-white/20"></div>
          <div class="flex items-center gap-1 text-rose-400 font-bold">
            <i data-lucide="skull" class="w-3.5 h-3.5"></i>
            <span id="hud-deaths">0</span>
          </div>
        </div>

        <button onclick="toggleLeaderboard()" class="w-9 h-9 rounded-lg bg-white/10 hover:bg-white/20 border border-white/15 flex items-center justify-center transition press-effect text-white/90">
          <i data-lucide="users" class="w-4 h-4"></i>
        </button>
      </div>
    </header>

    <!-- ★ ROBLOX風 左上チャットボックス ★ -->
    <div id="roblox-chat" class="absolute top-14 left-3 w-80 max-w-[calc(100vw-24px)] z-20 transition-all duration-200">
      <div class="roblox-glass border border-white/15 rounded-xl p-2.5 shadow-2xl flex flex-col gap-2">
        <!-- メッセージ履歴 -->
        <div id="chat-messages" class="h-28 overflow-y-auto scrollbar-thin text-xs space-y-1.5 pr-1">
          <div class="text-slate-400 text-[11px]">[System] Roblox Pastel Obby Server #382 に接続しました。</div>
          <div class="text-slate-400 text-[11px]">[System] [WASD/矢印]で移動、[Space]で3段ジャンプ!赤ブロックに注意!</div>
          <div class="text-pink-300 font-bold text-[11px]">
            <span class="text-white/70">[Player]:</span> こんにちは!可愛いアバターでObby制覇するぞ〜🌸
          </div>
        </div>
        <!-- チャット入力欄 -->
        <form onsubmit="handleChatSubmit(event)" class="flex gap-1.5">
          <input id="chat-input" type="text" placeholder="チャットを入力... (例: /e dance)" class="flex-1 bg-black/50 border border-white/20 rounded-lg px-2.5 py-1 text-xs text-white placeholder-white/40 focus:outline-none focus:border-pink-400">
          <button type="submit" class="px-3 py-1 bg-pink-500 hover:bg-pink-600 rounded-lg text-xs font-bold">送信</button>
        </form>
      </div>
    </div>

    <!-- ★ ROBLOX風 右上 Leaderboard (プレイヤーリスト) ★ -->
    <div id="roblox-leaderboard" class="absolute top-14 right-3 w-56 z-20 roblox-glass border border-white/15 rounded-xl p-2.5 shadow-2xl">
      <div class="text-[11px] font-bold text-slate-400 uppercase tracking-wider pb-1.5 border-b border-white/10 flex justify-between">
        <span>Players</span>
        <span>Stage</span>
      </div>
      <div class="mt-2 space-y-1 text-xs">
        <div class="flex items-center justify-between p-1.5 rounded-lg bg-pink-500/20 border border-pink-400/30">
          <div class="flex items-center gap-1.5">
            <span class="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
            <span class="font-bold text-pink-300">You (Chibi)</span>
          </div>
          <span id="lb-stage" class="font-black text-amber-300">Stage 1</span>
        </div>
        <div class="flex items-center justify-between p-1.5 rounded-lg text-slate-300">
          <div class="flex items-center gap-1.5">
            <span class="w-2 h-2 rounded-full bg-slate-500"></span>
            <span>NoobMaster_99</span>
          </div>
          <span class="text-slate-400">Stage 4</span>
        </div>
        <div class="flex items-center justify-between p-1.5 rounded-lg text-slate-300">
          <div class="flex items-center gap-1.5">
            <span class="w-2 h-2 rounded-full bg-slate-500"></span>
            <span>PastelQueen🌸</span>
          </div>
          <span class="text-slate-400">Stage 6</span>
        </div>
      </div>
    </div>

    <!-- ★ チェックポイント通知 (Stage Saved) ★ -->
    <div id="checkpoint-toast" class="absolute top-20 left-1/2 -translate-x-1/2 -translate-y-10 opacity-0 pointer-events-none transition-all duration-300 z-40 bg-emerald-500/90 text-white font-black px-5 py-2 rounded-2xl shadow-xl flex items-center gap-2 border border-emerald-300">
      <i data-lucide="check-circle" class="w-5 h-5"></i>
      <span id="checkpoint-msg">STAGE 2 CHECKPOINT REACHED!</span>
    </div>

    <!-- ★ ROBLOX STUDIO ツールバー (Studio Mode時に出現) ★ -->
    <div id="studio-toolbar" class="hidden absolute top-14 left-1/2 -translate-x-1/2 z-30 roblox-glass border border-purple-400/40 rounded-2xl p-2 shadow-2xl flex-wrap items-center gap-2">
      <span id="studio-selection-info" class="text-xs font-bold text-purple-200 px-2">パーツを選択してください</span>
      <div class="h-4 w-[1px] bg-white/20"></div>
      <button onclick="studioAddPart('normal')" class="px-2.5 py-1 bg-pink-500/30 hover:bg-pink-500/50 border border-pink-400/50 rounded-lg text-xs font-bold text-pink-200">+ 足場</button>
      <button onclick="studioAddPart('kill')" class="px-2.5 py-1 bg-rose-500/30 hover:bg-rose-500/50 border border-rose-400/50 rounded-lg text-xs font-bold text-rose-200">+ キルブロック</button>
      <button onclick="studioAddPart('bounce')" class="px-2.5 py-1 bg-amber-500/30 hover:bg-amber-500/50 border border-amber-400/50 rounded-lg text-xs font-bold text-amber-200">+ バウンス台</button>
      <button onclick="studioAddPart('checkpoint')" class="px-2.5 py-1 bg-sky-500/30 hover:bg-sky-500/50 border border-sky-400/50 rounded-lg text-xs font-bold text-sky-200">+ 旗</button>
      <div class="h-4 w-[1px] bg-white/20"></div>
      <div class="flex gap-1">
        <button onclick="studioMoveSelected(0, 1, 0)" class="px-2 py-1 bg-white/10 hover:bg-white/20 rounded text-xs">↑ 上</button>
        <button onclick="studioMoveSelected(0, -1, 0)" class="px-2 py-1 bg-white/10 hover:bg-white/20 rounded text-xs">↓ 下</button>
        <button onclick="studioMoveSelected(0, 0, -1)" class="px-2 py-1 bg-white/10 hover:bg-white/20 rounded text-xs">奥</button>
        <button onclick="studioMoveSelected(0, 0, 1)" class="px-2 py-1 bg-white/10 hover:bg-white/20 rounded text-xs">手前</button>
      </div>
      <button onclick="studioDeleteSelected()" class="px-2.5 py-1 bg-red-600 hover:bg-red-500 rounded-lg text-xs font-bold text-white">削除</button>
      <button onclick="testPlayCustomGame()" class="px-3 py-1 bg-gradient-to-r from-emerald-500 to-teal-600 hover:opacity-90 rounded-lg text-xs font-black text-white shadow">▶ テストプレイ</button>
    </div>

    <!-- ★ 操作ヒントガイド (画面左下) ★ -->
    <div class="absolute bottom-5 left-5 pointer-events-none z-10 hidden sm:flex flex-col gap-1 text-[11px] text-white/80 bg-black/60 backdrop-blur px-3 py-2 rounded-xl border border-white/10">
      <div>[WASD / 矢印] : 移動 | [Space] : <span class="text-pink-300 font-bold">連続3段ジャンプ!</span></div>
      <div>[Shift] : ダッシュ | [マウスドラッグ] : 360°カメラ回転</div>
      <div class="text-rose-300 font-bold">⚠️ 赤いキルブロック・溶岩に触れるとOOF即死!</div>
    </div>

    <!-- ★ モバイル用 仮想タッチコントローラー ★ -->
    <div class="absolute bottom-6 left-6 z-20 flex flex-col items-center gap-1 md:hidden select-none">
      <button id="btn-up" class="w-12 h-12 bg-white/20 active:bg-pink-500/60 backdrop-blur rounded-2xl shadow-lg border border-white/20 flex items-center justify-center font-black text-white text-base">▲</button>
      <div class="flex gap-2">
        <button id="btn-left" class="w-12 h-12 bg-white/20 active:bg-pink-500/60 backdrop-blur rounded-2xl shadow-lg border border-white/20 flex items-center justify-center font-black text-white text-base">◀</button>
        <button id="btn-down" class="w-12 h-12 bg-white/20 active:bg-pink-500/60 backdrop-blur rounded-2xl shadow-lg border border-white/20 flex items-center justify-center font-black text-white text-base">▼</button>
        <button id="btn-right" class="w-12 h-12 bg-white/20 active:bg-pink-500/60 backdrop-blur rounded-2xl shadow-lg border border-white/20 flex items-center justify-center font-black text-white text-base">▶</button>
      </div>
    </div>

    <div class="absolute bottom-6 right-6 z-20 flex items-center gap-3 md:hidden select-none">
      <button id="btn-sprint" class="w-12 h-12 bg-purple-500/40 active:bg-purple-600/80 backdrop-blur rounded-2xl shadow-lg border border-purple-300/30 text-white text-xs font-black">
        走る
      </button>
      <button id="btn-jump" class="w-16 h-16 bg-gradient-to-tr from-pink-500 to-rose-400 active:scale-95 rounded-full shadow-2xl text-white text-sm font-black flex flex-col items-center justify-center border-2 border-white/80">
        <span>JUMP</span>
        <span class="text-[9px] text-pink-100 font-normal">3段可</span>
      </button>
    </div>
  </div>

  <!-- ==========================================================
       2. ROBLOX 公式風 ESC メニューモーダル
       ========================================================== -->
  <div id="roblox-esc-modal" class="fixed inset-0 z-50 bg-black/75 backdrop-blur-md hidden items-center justify-center p-4">
    <div class="bg-slate-900 border border-white/15 rounded-3xl max-w-md w-full p-6 shadow-2xl flex flex-col gap-4">
      <div class="flex items-center justify-between border-b border-white/10 pb-3">
        <div class="flex items-center gap-2">
          <div class="w-6 h-6 bg-white rotate-12 rounded-[2px] flex items-center justify-center">
            <div class="w-2 h-2 bg-slate-950 rotate-12"></div>
          </div>
          <h2 class="font-black text-lg text-white">Roblox Experience Menu</h2>
        </div>
        <button onclick="toggleRobloxMenu()" class="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 text-slate-300 flex items-center justify-center">✕</button>
      </div>

      <div class="space-y-2.5">
        <button onclick="resetCharacter()" class="w-full py-3 bg-rose-500/20 hover:bg-rose-500/30 border border-rose-500/40 rounded-2xl text-rose-300 font-bold text-sm flex items-center justify-center gap-2 transition">
          <i data-lucide="rotate-ccw" class="w-4 h-4"></i>
          <span>Reset Character (リスポーン)</span>
        </button>
        <button onclick="openAvatarStudio(); toggleRobloxMenu();" class="w-full py-3 bg-pink-500/20 hover:bg-pink-500/30 border border-pink-500/40 rounded-2xl text-pink-300 font-bold text-sm flex items-center justify-center gap-2 transition">
          <i data-lucide="palette" class="w-4 h-4"></i>
          <span>Avatar Customizer (アバター工房を開く)</span>
        </button>
        <button onclick="openGameDiscovery(); toggleRobloxMenu();" class="w-full py-3 bg-cyan-500/20 hover:bg-cyan-500/30 border border-cyan-500/40 rounded-2xl text-cyan-300 font-bold text-sm flex items-center justify-center gap-2 transition">
          <i data-lucide="compass" class="w-4 h-4"></i>
          <span>Discover Games (ゲーム選択)</span>
        </button>
        <button onclick="toggleRobloxMenu()" class="w-full py-3 bg-white/10 hover:bg-white/20 border border-white/15 rounded-2xl text-white font-bold text-sm flex items-center justify-center transition">
          <span>Resume (ゲームに戻る)</span>
        </button>
      </div>
    </div>
  </div>

  <!-- ==========================================================
       ROBLOX DISCOVER GAMES モーダル (ゲーム選択)
       ========================================================== -->
  <div id="roblox-discovery-modal" class="fixed inset-0 z-50 bg-black/80 backdrop-blur-md hidden items-center justify-center p-4">
    <div class="bg-slate-900 border border-white/15 rounded-3xl max-w-xl w-full p-6 shadow-2xl flex flex-col gap-4">
      <div class="flex items-center justify-between border-b border-white/10 pb-3">
        <div class="flex items-center gap-2">
          <i data-lucide="compass" class="w-5 h-5 text-cyan-400"></i>
          <h2 class="font-black text-lg text-white">Roblox Games Discovery</h2>
        </div>
        <button onclick="closeGameDiscovery()" class="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 text-slate-300 flex items-center justify-center">✕</button>
      </div>

      <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <!-- Obby -->
        <button onclick="switchGameMode('obby')" class="p-3.5 bg-pink-500/10 hover:bg-pink-500/20 border border-pink-400/30 rounded-2xl text-left transition flex flex-col gap-1">
          <div class="text-sm font-black text-pink-300 flex items-center gap-1.5">
            <span>🌸</span> <span>Pastel Obby Adventure</span>
          </div>
          <p class="text-[11px] text-slate-400">全6ステージ!赤いブロックを跳び越える王道アスレチック</p>
        </button>

        <!-- Lava -->
        <button onclick="switchGameMode('lava')" class="p-3.5 bg-rose-500/10 hover:bg-rose-500/20 border border-rose-400/30 rounded-2xl text-left transition flex flex-col gap-1">
          <div class="text-sm font-black text-rose-300 flex items-center gap-1.5">
            <span>🌋</span> <span>The Floor is LAVA!</span>
          </div>
          <p class="text-[11px] text-slate-400">競り上がる溶岩から高台へ逃げろ!30秒間生き残るサバイバル</p>
        </button>

        <!-- Pet & Coins -->
        <button onclick="switchGameMode('pets')" class="p-3.5 bg-amber-500/10 hover:bg-amber-500/20 border border-amber-400/30 rounded-2xl text-left transition flex flex-col gap-1">
          <div class="text-sm font-black text-amber-300 flex items-center gap-1.5">
            <span>🐾</span> <span>Pet & Coin Paradise</span>
          </div>
          <p class="text-[11px] text-slate-400">散らばるコインを集めて卵ガチャ!可愛いペットをお供にしよう</p>
        </button>

        <!-- Custom Studio -->
        <button onclick="switchGameMode('custom')" class="p-3.5 bg-purple-500/10 hover:bg-purple-500/20 border border-purple-400/30 rounded-2xl text-left transition flex flex-col gap-1">
          <div class="text-sm font-black text-purple-300 flex items-center gap-1.5">
            <span>🛠️</span> <span>My Custom Studio World</span>
          </div>
          <p class="text-[11px] text-slate-400">自分で配置・作成したオリジナルステージをプレイ!</p>
        </button>
      </div>
    </div>
  </div>

  <!-- ==========================================================
       3. アバタークリエイター・ドロワー (スライドパネル)
       ========================================================== -->
  <div id="avatar-drawer" class="fixed inset-y-0 right-0 w-full max-w-md bg-white text-slate-700 shadow-2xl z-50 transform translate-x-full transition-transform duration-300 flex flex-col border-l border-pink-200">
    <div class="p-4 bg-gradient-to-r from-pink-50 via-purple-50 to-indigo-50 border-b border-pink-100 flex items-center justify-between">
      <div class="flex items-center gap-2">
        <div class="w-8 h-8 rounded-xl bg-gradient-to-tr from-pink-500 to-purple-500 flex items-center justify-center text-white shadow">
          <i data-lucide="sparkles" class="w-4 h-4"></i>
        </div>
        <div>
          <h3 class="font-extrabold text-sm text-slate-800">Avatar Studio</h3>
          <p class="text-[10px] text-pink-500 font-bold">スタイル・前髪・衣装をリアルタイム編集</p>
        </div>
      </div>
      <button onclick="closeAvatarStudio()" class="w-8 h-8 rounded-xl bg-white border border-pink-200 hover:bg-pink-50 flex items-center justify-center text-slate-500">
        ✕
      </button>
    </div>

    <!-- カテゴリタブ -->
    <div class="flex border-b border-pink-100 px-3 bg-white gap-1 overflow-x-auto scrollbar-thin">
      <button onclick="selectCategory('face')" id="cat-face" class="cat-tab py-2.5 px-3 text-xs font-extrabold border-b-2 border-pink-500 text-pink-600 whitespace-nowrap">顔・目元</button>
      <button onclick="selectCategory('hair')" id="cat-hair" class="cat-tab py-2.5 px-3 text-xs font-bold border-b-2 border-transparent text-slate-500 whitespace-nowrap">ヘア・前髪</button>
      <button onclick="selectCategory('clothes')" id="cat-clothes" class="cat-tab py-2.5 px-3 text-xs font-bold border-b-2 border-transparent text-slate-500 whitespace-nowrap">衣装・スカート</button>
      <button onclick="selectCategory('accessory')" id="cat-accessory" class="cat-tab py-2.5 px-3 text-xs font-bold border-b-2 border-transparent text-slate-500 whitespace-nowrap">アクセ・頭具</button>
      <button onclick="selectCategory('body')" id="cat-body" class="cat-tab py-2.5 px-3 text-xs font-bold border-b-2 border-transparent text-slate-500 whitespace-nowrap">体型微調整</button>
    </div>

    <!-- カスタマイザーオプション -->
    <div id="customizer-options" class="flex-1 overflow-y-auto p-4 space-y-4 scrollbar-thin"></div>

    <!-- 保存&完了ボタン -->
    <div class="p-3 border-t border-pink-100 bg-pink-50/50 flex gap-2">
      <button onclick="randomizeAvatar()" class="px-3 py-2.5 bg-white border border-pink-200 text-xs font-bold text-pink-600 rounded-xl hover:bg-pink-100 flex items-center gap-1">
        <i data-lucide="dices" class="w-3.5 h-3.5"></i>
        <span>ランダム</span>
      </button>
      <button onclick="closeAvatarStudio()" class="flex-1 py-2.5 bg-gradient-to-r from-pink-500 to-purple-600 text-white font-black text-xs rounded-xl shadow-md hover:opacity-90 flex items-center justify-center gap-1.5">
        <i data-lucide="check" class="w-4 h-4"></i>
        <span>ワールドに反映して遊ぶ!</span>
      </button>
    </div>
  </div>

  <!-- ==========================================================
       4. JAVASCRIPT: ゲーム&アバターエンジン
       ========================================================== -->
  <script>
    /* ----------------------------------------------------------
       アバターデータ構造
       ---------------------------------------------------------- */
    const avatar = {
      // 表情・目元
      skinColor: '#fff5f5',
      eyeType: 'starry',
      eyeColor: '#818cf8',
      mouthType: 'open',
      eyepatch: 'medical',
      eyepatchColor: '#ffffff',
      blushIntensity: 0.5,

      // 髪型
      bangType: 'parted',      // parted (ふんわり分け前髪), straight (ぱっつん), sideSwept (ななめ)
      hairStyle: 'twinBraids', // twinBraids, twintail, wolfCool, spikyCool, bob
      hairColor: '#e2e8f0',
      hasAhoge: true,

      // 洋服
      topType: 'dolmanSweat',
      topColor: '#93c5fd',
      hasSkirt: true,
      skirtColor: '#ffffff',
      hasChestRibbon: true,
      ribbonColor: '#f472b6',
      shoeColor: '#ffffff',

      // アクセサリー
      headAcc: 'sunglasses',
      backAcc: 'none',
      weapon: 'none',

      // スレンダープロポーション
      waistScale: 0.75,
      headScale: 1.05,
      legLength: 1.0,
      sleeveVolume: 1.15,

      // アニメーション状態
      isDancing: false
    };

    /* ----------------------------------------------------------
       Three.js テクスチャ生成 (瞳・口・Studsブロック)
       ---------------------------------------------------------- */
    function createEyeTexture(type, eyeColorHex, isLeftEye) {
      const c = document.createElement('canvas');
      c.width = 256; c.height = 256;
      const ctx = c.getContext('2d');
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, 256, 256);
      const cx = 128, cy = 135;

      ctx.fillStyle = '#0f172a';
      ctx.beginPath();
      ctx.ellipse(cx, cy, 78, 86, 0, 0, Math.PI * 2);
      ctx.fill();

      const grad = ctx.createLinearGradient(0, cy - 50, 0, cy + 60);
      grad.addColorStop(0, eyeColorHex);
      grad.addColorStop(1, '#1e1b4b');
      ctx.fillStyle = grad;
      ctx.beginPath();
      ctx.ellipse(cx, cy + 5, 65, 65, 0, 0, Math.PI * 2);
      ctx.fill();

      // キラキラハイライト
      ctx.fillStyle = '#ffffff';
      ctx.beginPath();
      ctx.arc(cx - 20, cy - 18, 16, 0, Math.PI * 2);
      ctx.arc(cx + 22, cy + 22, 10, 0, Math.PI * 2);
      ctx.arc(cx - 15, cy + 28, 5, 0, Math.PI * 2);
      ctx.fill();
      ctx.fillRect(cx + 10, cy - 22, 4, 16);
      ctx.fillRect(cx + 4, cy - 16, 16, 4);

      // アイライン
      ctx.strokeStyle = '#1e293b';
      ctx.lineWidth = 14;
      ctx.beginPath();
      ctx.arc(cx, cy - 30, 85, Math.PI * 1.15, Math.PI * 1.85);
      ctx.stroke();

      const sideDir = isLeftEye ? -1 : 1;
      ctx.lineWidth = 7;
      ctx.beginPath();
      ctx.moveTo(cx + (60 * sideDir), cy - 65);
      ctx.lineTo(cx + (85 * sideDir), cy - 80);
      ctx.stroke();

      return new THREE.CanvasTexture(c);
    }

    function createMouthTexture(type) {
      const c = document.createElement('canvas');
      c.width = 128; c.height = 128;
      const ctx = c.getContext('2d');
      const cx = 64, cy = 64;

      ctx.fillStyle = '#e11d48';
      ctx.beginPath();
      ctx.ellipse(cx, cy, 14, 10, 0, 0, Math.PI * 2);
      ctx.fill();

      ctx.fillStyle = '#fda4af';
      ctx.beginPath();
      ctx.ellipse(cx, cy + 3, 9, 6, 0, 0, Math.PI * 2);
      ctx.fill();
      return new THREE.CanvasTexture(c);
    }

    // Roblox特有のスタッド(Studs)テクスチャ
    function createStudTexture(baseColorHex) {
      const c = document.createElement('canvas');
      c.width = 64; c.height = 64;
      const ctx = c.getContext('2d');
      ctx.fillStyle = baseColorHex;
      ctx.fillRect(0, 0, 64, 64);

      // スタッドの円柱突起シャドウ&ハイライト
      ctx.fillStyle = 'rgba(0,0,0,0.12)';
      ctx.beginPath();
      ctx.arc(32, 34, 15, 0, Math.PI * 2);
      ctx.fill();

      ctx.fillStyle = 'rgba(255,255,255,0.2)';
      ctx.beginPath();
      ctx.arc(32, 30, 14, 0, Math.PI * 2);
      ctx.fill();

      ctx.fillStyle = baseColorHex;
      ctx.beginPath();
      ctx.arc(32, 32, 13, 0, Math.PI * 2);
      ctx.fill();

      const tex = new THREE.CanvasTexture(c);
      tex.wrapS = THREE.RepeatWrapping;
      tex.wrapT = THREE.RepeatWrapping;
      return tex;
    }

    /* ----------------------------------------------------------
       アバター3Dモデルビルダー
       ---------------------------------------------------------- */
    function buildChibiAvatar() {
      const group = new THREE.Group();

      const skinMat = new THREE.MeshStandardMaterial({ color: avatar.skinColor, roughness: 0.85 });
      const hairMat = new THREE.MeshStandardMaterial({ color: avatar.hairColor, roughness: 0.45 });
      const topMat = new THREE.MeshStandardMaterial({ color: avatar.topColor, roughness: 0.7 });
      const skirtMat = new THREE.MeshStandardMaterial({ color: avatar.skirtColor, roughness: 0.6 });
      const ribbonMat = new THREE.MeshStandardMaterial({ color: avatar.ribbonColor, roughness: 0.4 });
      const shoeMat = new THREE.MeshStandardMaterial({ color: avatar.shoeColor, roughness: 0.5 });
      const whiteMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.9 });

      // 1. 頭部
      const headPivot = new THREE.Group();
      headPivot.position.y = 1.05;
      headPivot.scale.set(avatar.headScale, avatar.headScale, avatar.headScale);
      group.add(headPivot);

      const headGeo = new THREE.SphereGeometry(0.38, 32, 32);
      headGeo.scale(1.0, 0.95, 0.95);
      const headMesh = new THREE.Mesh(headGeo, skinMat);
      headMesh.castShadow = true;
      headPivot.add(headMesh);

      // チーク
      const cheekGeo = new THREE.PlaneGeometry(0.12, 0.06);
      const cheekMat = new THREE.MeshBasicMaterial({ color: 0xf43f5e, transparent: true, opacity: 0.35, depthWrite: false });
      const cheekL = new THREE.Mesh(cheekGeo, cheekMat); cheekL.position.set(-0.18, -0.06, 0.35); cheekL.rotation.y = -0.3; headPivot.add(cheekL);
      const cheekR = new THREE.Mesh(cheekGeo, cheekMat); cheekR.position.set(0.18, -0.06, 0.35); cheekR.rotation.y = 0.3; headPivot.add(cheekR);

      // 目
      const eyeGeo = new THREE.PlaneGeometry(0.18, 0.18);
      const eyeR = new THREE.Mesh(eyeGeo, new THREE.MeshBasicMaterial({ map: createEyeTexture(avatar.eyeType, avatar.eyeColor, false), transparent: true }));
      eyeR.position.set(0.13, 0.02, 0.37); eyeR.rotation.y = 0.22; headPivot.add(eyeR);

      if (avatar.eyepatch === 'none') {
        const eyeL = new THREE.Mesh(eyeGeo, new THREE.MeshBasicMaterial({ map: createEyeTexture(avatar.eyeType, avatar.eyeColor, true), transparent: true }));
        eyeL.position.set(-0.13, 0.02, 0.37); eyeL.rotation.y = -0.22; headPivot.add(eyeL);
      } else {
        // 医療ガーゼ眼帯
        const patchGroup = new THREE.Group();
        const gauzeMesh = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.14, 0.02), new THREE.MeshStandardMaterial({ color: avatar.eyepatchColor, roughness: 0.8 }));
        patchGroup.add(gauzeMesh);
        const strap = new THREE.Mesh(new THREE.BoxGeometry(0.48, 0.015, 0.01), new THREE.MeshBasicMaterial({ color: 0x94a3b8 }));
        strap.rotation.z = 0.45; strap.position.z = -0.01; patchGroup.add(strap);
        patchGroup.position.set(-0.13, 0.02, 0.37); patchGroup.rotation.y = -0.22; headPivot.add(patchGroup);
      }

      // 口
      const mouth = new THREE.Mesh(new THREE.PlaneGeometry(0.1, 0.1), new THREE.MeshBasicMaterial({ map: createMouthTexture(avatar.mouthType), transparent: true }));
      mouth.position.set(0, -0.12, 0.375); headPivot.add(mouth);

      // ヘア&分け前髪
      const hairGroup = new THREE.Group(); headPivot.add(hairGroup);
      const bangGeo = new THREE.SphereGeometry(0.41, 24, 16, 0, Math.PI * 2, 0, Math.PI * 0.52);
      const bangMesh = new THREE.Mesh(bangGeo, hairMat); bangMesh.position.y = 0.02; hairGroup.add(bangMesh);

      // ふんわりセンター分け前髪
      if (avatar.bangType === 'parted') {
        [-1, 1].forEach(sign => {
          const strandGeo = new THREE.ConeGeometry(0.08, 0.28, 12);
          strandGeo.scale(1, 1, 0.4);
          strandGeo.translate(0, -0.14, 0);
          const strand = new THREE.Mesh(strandGeo, hairMat);
          strand.position.set(0.12 * sign, 0.24, 0.36);
          strand.rotation.set(-0.25, 0.2 * sign, -0.45 * sign);
          hairGroup.add(strand);
        });
      }

      // おさげツインブレイド
      if (avatar.hairStyle === 'twinBraids') {
        [-1, 1].forEach(sign => {
          const braid = new THREE.Group();
          for (let i = 0; i < 5; i++) {
            const knot = new THREE.Mesh(new THREE.SphereGeometry(0.08 - i * 0.008, 12, 12), hairMat);
            knot.scale.set(0.8, 1.2, 0.9);
            knot.position.set(Math.sin(i * 0.4) * 0.03 * sign, -i * 0.11, Math.cos(i * 0.4) * 0.02);
            braid.add(knot);
          }
          const rib = new THREE.Mesh(new THREE.TorusGeometry(0.05, 0.018, 8, 16), ribbonMat);
          rib.position.y = -0.46; braid.add(rib);
          braid.position.set(0.3 * sign, 0.05, 0.1); hairGroup.add(braid);
        });
      }

      // アホ毛
      if (avatar.hasAhoge) {
        const ahogeCurve = new THREE.CatmullRomCurve3([
          new THREE.Vector3(0, 0.38, 0),
          new THREE.Vector3(0.08, 0.52, 0.05),
          new THREE.Vector3(0.15, 0.58, -0.02),
          new THREE.Vector3(0.12, 0.62, -0.08)
        ]);
        hairGroup.add(new THREE.Mesh(new THREE.TubeGeometry(ahogeCurve, 12, 0.015, 8, false), hairMat));
      }

      // 頭乗せサングラス
      if (avatar.headAcc === 'sunglasses') {
        const shades = new THREE.Group(); shades.position.set(0, 0.3, 0.2); shades.rotation.x = -0.55;
        const gMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.1, transparent: true, opacity: 0.7 });
        [-0.14, 0.14].forEach(x => {
          const l = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.12, 0.02), gMat); l.position.x = x; shades.add(l);
          const f = new THREE.Mesh(new THREE.TorusGeometry(0.08, 0.012, 8, 16), new THREE.MeshStandardMaterial({ color: 0xe2e8f0 })); f.position.x = x; shades.add(f);
        });
        headPivot.add(shades);
      }

      // 2. 胴体&萌え袖洋服
      const bodyGroup = new THREE.Group(); bodyGroup.position.y = 0.65; group.add(bodyGroup);
      const torsoW = 0.32 * avatar.waistScale;
      const torsoMesh = new THREE.Mesh(new THREE.CylinderGeometry(torsoW * 0.9, torsoW * 1.15, 0.42, 24), topMat);
      torsoMesh.castShadow = true; bodyGroup.add(torsoMesh);

      if (avatar.hasChestRibbon) {
        const rib = new THREE.Mesh(new THREE.TorusGeometry(0.05, 0.015, 8, 16), ribbonMat);
        rib.position.set(0, 0.12, torsoW + 0.02); bodyGroup.add(rib);
      }

      if (avatar.hasSkirt) {
        const skirt = new THREE.Mesh(new THREE.ConeGeometry(torsoW * 1.6, 0.25, 24, 1, true), skirtMat);
        skirt.position.y = -0.15; skirt.geometry.translate(0, -0.12, 0); bodyGroup.add(skirt);
        const lace = new THREE.Mesh(new THREE.TorusGeometry(torsoW * 1.6, 0.02, 8, 32), whiteMat);
        lace.position.y = -0.27; lace.rotation.x = Math.PI / 2; bodyGroup.add(lace);
      }

      // 萌え袖腕
      group.armLeft = new THREE.Group();
      group.armRight = new THREE.Group();
      [-1, 1].forEach(sign => {
        const arm = (sign === -1) ? group.armLeft : group.armRight;
        arm.position.set((torsoW + 0.12) * sign, 0.15, 0);
        arm.rotation.z = -0.25 * sign;

        const sleeve = new THREE.Mesh(new THREE.CylinderGeometry(0.09 * avatar.sleeveVolume, 0.16 * avatar.sleeveVolume, 0.38, 16), topMat);
        sleeve.geometry.translate(0, -0.18, 0); arm.add(sleeve);
        const cuff = new THREE.Mesh(new THREE.TorusGeometry(0.16 * avatar.sleeveVolume, 0.02, 8, 16), whiteMat);
        cuff.position.y = -0.37; cuff.rotation.x = Math.PI / 2; arm.add(cuff);
        const hand = new THREE.Mesh(new THREE.SphereGeometry(0.045, 12, 12), skinMat);
        hand.position.y = -0.38; arm.add(hand);
        bodyGroup.add(arm);
      });

      // 3. 脚&Y2K厚底スニーカー
      const legsGroup = new THREE.Group(); legsGroup.position.y = 0.42; group.add(legsGroup);
      group.legLeft = new THREE.Group();
      group.legRight = new THREE.Group();
      [-1, 1].forEach(sign => {
        const leg = (sign === -1) ? group.legLeft : group.legRight;
        leg.position.x = 0.12 * sign;
        const legMesh = new THREE.Mesh(new THREE.CylinderGeometry(0.055, 0.05, 0.38 * avatar.legLength, 16), skinMat);
        legMesh.geometry.translate(0, -0.18 * avatar.legLength, 0); leg.add(legMesh);

        // 厚底靴
        const shoe = new THREE.Group(); shoe.position.set(0, -0.36 * avatar.legLength, 0.04);
        shoe.add(new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.12, 0.22), shoeMat));
        const sole = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.06, 0.24), whiteMat); sole.position.y = -0.07; shoe.add(sole);
        leg.add(shoe);
        legsGroup.add(leg);
      });

      return group;
    }

    /* ----------------------------------------------------------
       ROBLOX OBBY 3Dワールド構築 & 物理エンジン
       ---------------------------------------------------------- */
    let scene, camera, renderer, playerMesh = null;
    let platforms = [], killBricks = [], checkpoints = [], stars = [], particles = [];

    // ★ マルチゲーム&Studio状態管理 ★
    let currentMode = 'obby'; // 'obby' | 'lava' | 'pets' | 'custom'
    let isStudioMode = false;
    let customStudioParts = [];
    let selectedStudioPart = null;
    let raycaster = new THREE.Raycaster();
    let mouse = new THREE.Vector2();

    // 溶岩サバイバル用
    let lavaMesh = null;
    let lavaHeight = -10;
    let lavaTimer = 30;

    // ペット用
    let userCoins = 0;
    let equippedPets = [];
    let coinCollectibles = [];

    const gameState = {
      currentStage: 1,
      maxStage: 6,
      deaths: 0,
      stars: 0,
      checkpointPos: new THREE.Vector3(0, 1.2, 0)
    };

    const player = {
      x: 0, y: 1.2, z: 0,
      vx: 0, vy: 0, vz: 0,
      jumpCount: 0,
      maxJumps: 3,
      speed: 6.2,
      sprintMult: 1.5,
      rotation: 0,
      isGrounded: false
    };

    const keys = { forward: false, backward: false, left: false, right: false, sprint: false };

    function initRobloxWorld() {
      const canvas = document.getElementById('game-canvas');
      const w = window.innerWidth, h = window.innerHeight;

      scene = new THREE.Scene();
      // Roblox風の快晴ブルースカイ
      scene.background = new THREE.Color(0x93c5fd);
      scene.fog = new THREE.FogExp2(0x93c5fd, 0.015);

      camera = new THREE.PerspectiveCamera(50, w / h, 0.1, 300);
      camera.position.set(0, 4, 8);

      renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
      renderer.setSize(w, h);
      renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
      renderer.shadowMap.enabled = true;
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;

      // ライティング
      const hemiLight = new THREE.HemisphereLight(0xffffff, 0xfce7f3, 0.85);
      scene.add(hemiLight);

      const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
      dirLight.position.set(30, 60, 40);
      dirLight.castShadow = true;
      dirLight.shadow.mapSize.width = 1024;
      dirLight.shadow.mapSize.height = 1024;
      scene.add(dirLight);

      // 初期ゲームワールド構築
      loadGameWorld('obby');

      setupInput();
      setupStudioMousePicker();
      window.addEventListener('resize', onWindowResize);
      requestAnimationFrame(gameLoop);
    }

    function onWindowResize() {
      if (!renderer || !camera) return;
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }

    /* ----------------------------------------------------------
       プレイヤーリスポーン・生成
       ---------------------------------------------------------- */
    function spawnPlayer() {
      if (playerMesh && scene) {
        scene.remove(playerMesh);
      }
      playerMesh = buildChibiAvatar();
      if (scene) {
        scene.add(playerMesh);
      }

      player.x = gameState.checkpointPos.x;
      player.y = gameState.checkpointPos.y;
      player.z = gameState.checkpointPos.z;
      player.vx = 0;
      player.vy = 0;
      player.vz = 0;
      player.jumpCount = 0;
      player.isGrounded = false;
    }

    /* ----------------------------------------------------------
       ワールド切り替えマネージャー (Multi-Games)
       ---------------------------------------------------------- */
    function clearSceneEntities() {
      platforms.forEach(p => scene.remove(p.mesh));
      killBricks.forEach(k => scene.remove(k.mesh));
      checkpoints.forEach(c => scene.remove(c.mesh));
      stars.forEach(s => scene.remove(s));
      coinCollectibles.forEach(c => scene.remove(c));
      customStudioParts.forEach(cp => scene.remove(cp.mesh));
      if (lavaMesh) { scene.remove(lavaMesh); lavaMesh = null; }

      platforms = []; killBricks = []; checkpoints = []; stars = []; coinCollectibles = [];
    }

    function loadGameWorld(mode) {
      clearSceneEntities();
      currentMode = mode;
      gameState.checkpointPos.set(0, 1.2, 0);

      const badge = document.getElementById('top-world-badge');
      const stageTxt = document.getElementById('top-stage-txt');
      const lavaHud = document.getElementById('lava-hud');
      const petHud = document.getElementById('pet-hud');

      if (lavaHud) lavaHud.classList.add('hidden');
      if (petHud) petHud.classList.add('hidden');

      if (mode === 'obby') {
        if (badge) badge.textContent = '🌸 Pastel Obby World';
        if (stageTxt) stageTxt.textContent = 'STAGE 1 / 6';
        scene.background = new THREE.Color(0x93c5fd);
        buildObbyStages();
      } else if (mode === 'lava') {
        if (badge) badge.textContent = '🌋 The Floor is LAVA!';
        if (stageTxt) stageTxt.textContent = 'ESCAPE TO ROOF';
        scene.background = new THREE.Color(0xfca5a5);
        if (lavaHud) {
          lavaHud.classList.remove('hidden');
          lavaHud.classList.add('flex');
        }
        buildLavaStages();
      } else if (mode === 'pets') {
        if (badge) badge.textContent = '🐾 Pet & Coin Paradise';
        if (stageTxt) stageTxt.textContent = 'COLLECT COINS';
        scene.background = new THREE.Color(0xa7f3d0);
        if (petHud) {
          petHud.classList.remove('hidden');
          petHud.classList.add('flex');
        }
        buildPetStages();
      } else if (mode === 'custom') {
        if (badge) badge.textContent = '🛠️ My Custom Studio World';
        if (stageTxt) stageTxt.textContent = 'USER CREATED';
        scene.background = new THREE.Color(0xd8b4fe);
        buildCustomStudioWorld();
      }

      spawnPlayer();
    }

    // 本格Roblox Obbyコース作成
    function buildObbyStages() {
      platforms = []; killBricks = []; checkpoints = []; stars = [];

      // ヘルパー: 足場ブロック生成
      const addBlock = (x, y, z, w, h, d, colorHex, isCheckpoint = false, stageNum = 1) => {
        const geo = new THREE.BoxGeometry(w, h, d);
        const tex = createStudTexture(colorHex);
        tex.repeat.set(Math.max(1, Math.round(w)), Math.max(1, Math.round(d)));
        const mat = new THREE.MeshStandardMaterial({ color: colorHex, map: tex, roughness: 0.4 });
        const mesh = new THREE.Mesh(geo, mat);
        mesh.position.set(x, y, z);
        mesh.receiveShadow = true; mesh.castShadow = true;
        scene.add(mesh);

        const platData = { mesh, minX: x - w / 2, maxX: x + w / 2, minZ: z - d / 2, maxZ: z + d / 2, topY: y + h / 2 };
        platforms.push(platData);

        if (isCheckpoint) {
          // チェックポイント旗&光るディスク
          const pad = new THREE.Mesh(
            new THREE.CylinderGeometry(1.2, 1.2, 0.08, 24),
            new THREE.MeshStandardMaterial({ color: 0x38bdf8, emissive: 0x0284c7, emissiveIntensity: 0.4 })
          );
          pad.position.set(x, y + h / 2 + 0.04, z);
          scene.add(pad);
          checkpoints.push({ stage: stageNum, x, y: y + h / 2 + 0.1, z, mesh: pad, reached: stageNum === 1 });
        }
        return platData;
      };

      // ヘルパー: 赤い即死キルブロック (Lava / Lasers)
      const addKillBrick = (x, y, z, w, h, d) => {
        const mesh = new THREE.Mesh(
          new THREE.BoxGeometry(w, h, d),
          new THREE.MeshStandardMaterial({ color: 0xef4444, emissive: 0xef4444, emissiveIntensity: 0.9 })
        );
        mesh.position.set(x, y, z);
        scene.add(mesh);
        killBricks.push({ mesh, minX: x - w / 2, maxX: x + w / 2, minY: y - h / 2, maxY: y + h / 2, minZ: z - d / 2, maxZ: z + d / 2 });
      };

      // ヘルパー: コレクタブル星
      const addStar = (x, y, z) => {
        const star = new THREE.Mesh(
          new THREE.OctahedronGeometry(0.35, 0),
          new THREE.MeshStandardMaterial({ color: 0xfbbf24, emissive: 0xf59e0b, emissiveIntensity: 0.7 })
        );
        star.position.set(x, y, z);
        scene.add(star);
        stars.push(star);
      };

      // STAGE 1: スポーン島
      addBlock(0, 0, 0, 10, 1, 10, '#f8fafc', true, 1);
      addStar(0, 1.8, -2);

      // STAGE 1 -> 2: パステル飛び石ロード
      addBlock(0, 0.8, -8, 3, 0.8, 3, '#fbcfe8');
      addBlock(4, 1.6, -13, 3, 0.8, 3, '#c7d2fe');
      addBlock(-3, 2.4, -18, 3, 0.8, 3, '#fed7aa');
      addStar(-3, 4.0, -18);

      // STAGE 2: チェックポイント島 (キルレーザー回避)
      addBlock(0, 3.2, -25, 10, 1, 8, '#f1f5f9', true, 2);
      addKillBrick(0, 4.0, -25, 9, 0.4, 0.4); // 飛び越えキルレーザー
      addKillBrick(0, 4.0, -28, 9, 0.4, 0.4);

      // STAGE 2 -> 3: 赤レンガ回避ジャンプ (赤ブロックを踏むとOOF)
      addBlock(0, 4.0, -34, 3, 0.8, 3, '#ffffff');
      addKillBrick(0, 4.0, -38, 5, 0.4, 3); // 間に溶岩ブロック
      addBlock(0, 4.5, -42, 3, 0.8, 3, '#ffffff');
      addStar(0, 6.0, -42);

      // STAGE 3: チェックポイント島 (回転障害物)
      addBlock(0, 5.0, -50, 10, 1, 10, '#f1f5f9', true, 3);
      // 回転スピナー棒
      const spinnerMesh = new THREE.Mesh(
        new THREE.BoxGeometry(9, 0.6, 0.6),
        new THREE.MeshStandardMaterial({ color: 0xef4444, emissive: 0xdc2626, emissiveIntensity: 0.8 })
      );
      spinnerMesh.position.set(0, 5.9, -50);
      scene.add(spinnerMesh);
      killBricks.push({ mesh: spinnerMesh, isRotating: true, minX: -4.5, maxX: 4.5, minY: 5.5, maxY: 6.3, minZ: -54.5, maxZ: -45.5 });

      // STAGE 3 -> 4: 3段ジャンプ必須の超高層パルクール
      addBlock(5, 7.0, -58, 2.5, 0.8, 2.5, '#e0e7ff');
      addBlock(0, 9.0, -64, 2.5, 0.8, 2.5, '#fce7f3');
      addBlock(-5, 11.0, -70, 2.5, 0.8, 2.5, '#dcfce7');
      addStar(-5, 12.8, -70);

      // STAGE 4: チェックポイント島
      addBlock(0, 12.0, -78, 10, 1, 10, '#ffffff', true, 4);

      // STAGE 5: レーザー網タイトロープ
      addBlock(0, 12.5, -88, 1.2, 0.8, 12, '#38bdf8');
      addKillBrick(0, 13.3, -85, 4, 0.3, 0.3);
      addKillBrick(0, 13.3, -91, 4, 0.3, 0.3);

      // STAGE 6: GOAL! ゴールデンビクトリーアイランド
      addBlock(0, 13.0, -104, 14, 1.2, 14, '#fef08a', true, 6);
      addStar(0, 15.0, -104);
      addStar(2, 15.0, -104);
      addStar(-2, 15.0, -104);
    }

    // ゲーム2: 溶岩上昇サバイバルワールド
    function buildLavaStages() {
      // 巨大な中央螺旋タワー
      const geo = new THREE.BoxGeometry(60, 2, 60);
      const floor = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x334155 }));
      floor.position.set(0, 0, 0);
      scene.add(floor);
      platforms.push({ mesh: floor, minX: -30, maxX: 30, minZ: -30, maxZ: 30, topY: 1 });

      // 上へ登る螺旋足場
      for (let i = 0; i < 18; i++) {
        const ang = i * 0.45;
        const rad = 10;
        const px = Math.cos(ang) * rad;
        const pz = Math.sin(ang) * rad;
        const py = 1.5 + i * 1.5;
        const blk = new THREE.Mesh(
          new THREE.BoxGeometry(4, 0.8, 4),
          new THREE.MeshStandardMaterial({ color: i % 2 === 0 ? 0xf472b6 : 0x38bdf8 })
        );
        blk.position.set(px, py, pz);
        scene.add(blk);
        platforms.push({ mesh: blk, minX: px - 2, maxX: px + 2, minZ: pz - 2, maxZ: pz + 2, topY: py + 0.4 });
      }

      // 頂上ゴールアイランド
      const topPlat = new THREE.Mesh(new THREE.CylinderGeometry(6, 6, 1, 24), new THREE.MeshStandardMaterial({ color: 0xfde047 }));
      topPlat.position.set(0, 29, 0);
      scene.add(topPlat);
      platforms.push({ mesh: topPlat, minX: -6, maxX: 6, minZ: -6, maxZ: 6, topY: 29.5 });

      // 赤くグツグツ上昇する溶岩平面
      lavaHeight = -5;
      lavaTimer = 35;
      const lavaGeo = new THREE.PlaneGeometry(120, 120);
      const lavaMat = new THREE.MeshBasicMaterial({ color: 0xef4444, transparent: true, opacity: 0.85, side: THREE.DoubleSide });
      lavaMesh = new THREE.Mesh(lavaGeo, lavaMat);
      lavaMesh.rotation.x = -Math.PI / 2;
      lavaMesh.position.set(0, lavaHeight, 0);
      scene.add(lavaMesh);
    }

    // ゲーム3: ペット&コイン集めアイランド
    function buildPetStages() {
      // 広大なパステルアイランド
      const island = new THREE.Mesh(new THREE.CylinderGeometry(24, 26, 2, 32), new THREE.MeshStandardMaterial({ color: 0xbbf7d0 }));
      island.position.set(0, 0, 0);
      scene.add(island);
      platforms.push({ mesh: island, minX: -24, maxX: 24, minZ: -24, maxZ: 24, topY: 1 });

      // キラキラコインを大量散布
      coinCollectibles = [];
      for (let i = 0; i < 20; i++) {
        const coin = new THREE.Mesh(
          new THREE.CylinderGeometry(0.5, 0.5, 0.15, 16),
          new THREE.MeshStandardMaterial({ color: 0xfacc15, emissive: 0xeab308, emissiveIntensity: 0.6 })
        );
        coin.rotation.x = Math.PI / 2;
        const ang = Math.random() * Math.PI * 2;
        const dist = Math.random() * 18 + 2;
        coin.position.set(Math.cos(ang) * dist, 1.8, Math.sin(ang) * dist);
        scene.add(coin);
        coinCollectibles.push(coin);
      }
    }

    /* ----------------------------------------------------------
       ★ ROBLOX STUDIO (ゲームを自分で作る機能) ★
       ---------------------------------------------------------- */
    function toggleStudioMode() {
      isStudioMode = !isStudioMode;
      const bar = document.getElementById('studio-toolbar');
      const btn = document.getElementById('studio-btn-label');

      if (isStudioMode) {
        bar.classList.remove('hidden');
        bar.classList.add('flex');
        btn.textContent = 'Studio 終了';
        if (currentMode !== 'custom') switchGameMode('custom');
      } else {
        bar.classList.add('hidden');
        bar.classList.remove('flex');
        btn.textContent = 'Studio (作成)';
      }
    }

    function buildCustomStudioWorld() {
      // 土台のベースプレート
      const base = new THREE.Mesh(new THREE.BoxGeometry(40, 1, 40), new THREE.MeshStandardMaterial({ color: 0xf1f5f9 }));
      base.position.set(0, 0, 0);
      scene.add(base);
      platforms.push({ mesh: base, minX: -20, maxX: 20, minZ: -20, maxZ: 20, topY: 0.5 });

      // 既存の保存パーツを再描画
      customStudioParts.forEach(cp => {
        scene.add(cp.mesh);
        registerStudioPartToPhysics(cp);
      });
    }

    // パーツの追加
    function studioAddPart(type) {
      let w = 4, h = 0.8, d = 4;
      let col = '#fbcfe8';
      let y = player.y + 0.5;
      let x = player.x + Math.sin(player.rotation) * 4;
      let z = player.z + Math.cos(player.rotation) * 4;

      if (type === 'kill') {
        col = '#ef4444';
        w = 5; h = 0.4; d = 2;
      } else if (type === 'bounce') {
        col = '#f59e0b';
        w = 3; h = 0.6; d = 3;
      } else if (type === 'checkpoint') {
        col = '#38bdf8';
        w = 3; h = 0.2; d = 3;
      }

      const geo = new THREE.BoxGeometry(w, h, d);
      const mat = new THREE.MeshStandardMaterial({
        color: col,
        emissive: type === 'kill' ? 0xef4444 : 0x000000,
        emissiveIntensity: type === 'kill' ? 0.7 : 0
      });
      const mesh = new THREE.Mesh(geo, mat);
      mesh.position.set(x, y, z);
      scene.add(mesh);

      const partData = { id: Date.now() + Math.random(), type, mesh, w, h, d, color: col };
      customStudioParts.push(partData);
      registerStudioPartToPhysics(partData);

      selectStudioPart(partData);
    }

    function registerStudioPartToPhysics(cp) {
      const p = cp.mesh.position;
      if (cp.type === 'normal' || cp.type === 'bounce') {
        platforms.push({
          mesh: cp.mesh,
          minX: p.x - cp.w / 2, maxX: p.x + cp.w / 2,
          minZ: p.z - cp.d / 2, maxZ: p.z + cp.d / 2,
          topY: p.y + cp.h / 2,
          isBounce: cp.type === 'bounce'
        });
      } else if (cp.type === 'kill') {
        killBricks.push({
          mesh: cp.mesh,
          minX: p.x - cp.w / 2, maxX: p.x + cp.w / 2,
          minY: p.y - cp.h / 2, maxY: p.y + cp.h / 2,
          minZ: p.z - cp.d / 2, maxZ: p.z + cp.d / 2
        });
      } else if (cp.type === 'checkpoint') {
        checkpoints.push({
          stage: checkpoints.length + 1,
          x: p.x, y: p.y + 0.2, z: p.z,
          mesh: cp.mesh, reached: false
        });
      }
    }

    function selectStudioPart(partData) {
      if (selectedStudioPart && selectedStudioPart.mesh) {
        selectedStudioPart.mesh.material.wireframe = false;
      }
      selectedStudioPart = partData;
      if (selectedStudioPart && selectedStudioPart.mesh) {
        selectedStudioPart.mesh.material.wireframe = true;
        document.getElementById('studio-selection-info').textContent = `選択中: ${selectedStudioPart.type} (X:${selectedStudioPart.mesh.position.x.toFixed(1)}, Y:${selectedStudioPart.mesh.position.y.toFixed(1)})`;
      }
    }

    function studioMoveSelected(dx, dy, dz) {
      if (!selectedStudioPart) return;
      selectedStudioPart.mesh.position.x += dx;
      selectedStudioPart.mesh.position.y += dy;
      selectedStudioPart.mesh.position.z += dz;
      // 物理判定を再計算
      recalculateCustomPhysics();
      selectStudioPart(selectedStudioPart);
    }

    function studioChangePartColor(hex) {
      if (!selectedStudioPart) return;
      selectedStudioPart.color = hex;
      selectedStudioPart.mesh.material.color.set(hex);
    }

    function studioDeleteSelected() {
      if (!selectedStudioPart) return;
      scene.remove(selectedStudioPart.mesh);
      customStudioParts = customStudioParts.filter(p => p.id !== selectedStudioPart.id);
      selectedStudioPart = null;
      document.getElementById('studio-selection-info').textContent = 'パーツを選択してください';
      recalculateCustomPhysics();
    }

    function studioClearAll() {
      customStudioParts.forEach(p => scene.remove(p.mesh));
      customStudioParts = [];
      selectedStudioPart = null;
      recalculateCustomPhysics();
    }

    function recalculateCustomPhysics() {
      platforms = platforms.filter(p => !customStudioParts.some(cp => cp.mesh === p.mesh));
      killBricks = killBricks.filter(k => !customStudioParts.some(cp => cp.mesh === k.mesh));
      checkpoints = checkpoints.filter(c => !customStudioParts.some(cp => cp.mesh === c.mesh));
      customStudioParts.forEach(cp => registerStudioPartToPhysics(cp));
    }

    function testPlayCustomGame() {
      toggleStudioMode();
      spawnPlayer();
      showCheckpointToast('🎮 自作ステージのテストプレイ開始!');
    }

    // 画面クリックでStudioパーツを選択
    function setupStudioMousePicker() {
      window.addEventListener('pointerdown', e => {
        if (!isStudioMode) return;
        if (e.target.closest('#studio-toolbar') || e.target.closest('header')) return;

        mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
        raycaster.setFromCamera(mouse, camera);

        const meshes = customStudioParts.map(cp => cp.mesh);
        const intersects = raycaster.intersectObjects(meshes);
        if (intersects.length > 0) {
          const hit = intersects[0].object;
          const found = customStudioParts.find(cp => cp.mesh === hit);
          if (found) selectStudioPart(found);
        }
      });
    }

    /* ----------------------------------------------------------
       ペットガチャ & ペット追従
       ---------------------------------------------------------- */
    function openPetEggHatch() {
      if (userCoins < 10) {
        showCheckpointToast('⚠️ コインが足りません!(必要: 10)');
        return;
      }
      userCoins -= 10;
      document.getElementById('pet-coin-count').textContent = userCoins;

      const petTypes = ['🐱 子猫ちゃん', '🐰 うさぎさん', '🐻 くまちゃん', '🦄 ユニコーン'];
      const petChoice = petTypes[Math.floor(Math.random() * petTypes.length)];
      showCheckpointToast(`🎉 ガチャ成功! 【${petChoice}】 が仲間になった!`);

      // 3Dペットメッシュ作成
      const petMesh = new THREE.Mesh(
        new THREE.SphereGeometry(0.24, 16, 16),
        new THREE.MeshStandardMaterial({ color: ['#fbcfe8', '#fed7aa', '#c7d2fe', '#fef08a'][equippedPets.length % 4] })
      );
      scene.add(petMesh);
      equippedPets.push(petMesh);
    }

    function switchGameMode(mode) {
      closeGameDiscovery();
      loadGameWorld(mode);
    }

    function openGameDiscovery() {
      document.getElementById('roblox-discovery-modal').classList.remove('hidden');
      document.getElementById('roblox-discovery-modal').classList.add('flex');
    }

    function closeGameDiscovery() {
      document.getElementById('roblox-discovery-modal').classList.add('hidden');
      document.getElementById('roblox-discovery-modal').classList.remove('flex');
    }

    // Roblox特有の「OOF!」死亡効果音&リスポーン
    let audioCtx = null;
    function playOofSound() {
      try {
        if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        if (audioCtx.state === 'suspended') audioCtx.resume();

        // 伝統的なRobloxの「OOF」に近いピッチフォール音響合成
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();
        osc.type = 'sawtooth';
        osc.connect(gain);
        gain.connect(audioCtx.destination);

        osc.frequency.setValueAtTime(420, audioCtx.currentTime);
        osc.frequency.exponentialRampToValueAtTime(120, audioCtx.currentTime + 0.28);

        gain.gain.setValueAtTime(0.3, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.28);

        osc.start();
        osc.stop(audioCtx.currentTime + 0.29);
      } catch (e) {}
    }

    function playJumpSound(step) {
      try {
        if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();
        osc.connect(gain);
        gain.connect(audioCtx.destination);
        const f = 340 + step * 160;
        osc.frequency.setValueAtTime(f, audioCtx.currentTime);
        osc.frequency.exponentialRampToValueAtTime(f * 1.6, audioCtx.currentTime + 0.12);
        gain.gain.setValueAtTime(0.18, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.12);
        osc.start(); osc.stop(audioCtx.currentTime + 0.13);
      } catch (e) {}
    }

    function resetCharacter() {
      playOofSound();
      gameState.deaths++;
      document.getElementById('hud-deaths').textContent = gameState.deaths;

      // 死亡パーティクル
      for (let i = 0; i < 15; i++) {
        const p = new THREE.Mesh(new THREE.BoxGeometry(0.18, 0.18, 0.18), new THREE.MeshBasicMaterial({ color: 0xf43f5e }));
        p.position.set(player.x, player.y + 0.5, player.z);
        scene.add(p);
        const a = Math.random() * Math.PI * 2;
        particles.push({ mesh: p, vx: Math.cos(a) * 3, vy: Math.random() * 4 + 2, vz: Math.sin(a) * 3, life: 0.5 });
      }

      spawnPlayer();
    }

    function triggerJump() {
      if (player.jumpCount < player.maxJumps) {
        player.jumpCount++;
        player.vy = 8.6;
        player.isGrounded = false;
        playJumpSound(player.jumpCount);

        // ジャンプリング演出
        const ring = new THREE.Mesh(
          new THREE.RingGeometry(0.1, 0.5, 24),
          new THREE.MeshBasicMaterial({ color: (player.jumpCount === 1 ? 0xf472b6 : 0x38bdf8), side: THREE.DoubleSide, transparent: true, opacity: 0.9 })
        );
        ring.rotation.x = -Math.PI / 2;
        ring.position.set(player.x, player.y + 0.05, player.z);
        scene.add(ring);
        particles.push({ mesh: ring, isRing: true, life: 0.35, maxLife: 0.35 });
      }
    }

    /* ----------------------------------------------------------
       ゲームメインループ (物理演算・カメラ・コリジョン)
       ---------------------------------------------------------- */
    let lastTime = performance.now();
    function gameLoop(now) {
      requestAnimationFrame(gameLoop);
      const dt = Math.min((now - lastTime) / 1000, 0.1);
      lastTime = now;

      // 1. 移動入力処理
      let dx = 0, dz = 0;
      if (keys.forward) dz -= 1;
      if (keys.backward) dz += 1;
      if (keys.left) dx -= 1;
      if (keys.right) dx += 1;

      const len = Math.hypot(dx, dz);
      if (len > 0) {
        dx /= len; dz /= len;
        const curSpd = player.speed * (keys.sprint ? player.sprintMult : 1.0);
        player.vx = dx * curSpd;
        player.vz = dz * curSpd;
        player.rotation = Math.atan2(dx, dz);
        avatar.isDancing = false;
      } else {
        player.vx *= 0.8;
        player.vz *= 0.8;
      }

      // 2. 重力
      const gravity = 18.0;
      player.vy -= gravity * dt;

      const prevY = player.y;
      player.x += player.vx * dt;
      player.y += player.vy * dt;
      player.z += player.vz * dt;

      // 3. 足場着地判定
      let landed = false;
      for (const plat of platforms) {
        if (
          player.x >= plat.minX - 0.28 && player.x <= plat.maxX + 0.28 &&
          player.z >= plat.minZ - 0.28 && player.z <= plat.maxZ + 0.28
        ) {
          if (prevY >= plat.topY - 0.05 && player.y <= plat.topY) {
            player.y = plat.topY;
            player.vy = 0;
            landed = true;

            // バウンス台(大ジャンプ)
            if (plat.isBounce) {
              player.vy = 14;
              playJumpSound(3);
            }
            break;
          }
        }
      }

      if (landed) {
        if (!player.isGrounded) player.jumpCount = 0;
        player.isGrounded = true;
      } else {
        player.isGrounded = false;
      }

      // 4. 赤いキルブロック (Kill Bricks) コリジョン判定
      for (const kb of killBricks) {
        if (kb.isRotating && kb.mesh) {
          kb.mesh.rotation.y += dt * 1.5;
        }
        const dist = Math.hypot(player.x - kb.mesh.position.x, player.z - kb.mesh.position.z);
        if (dist < 4.8 && Math.abs(player.y - kb.mesh.position.y) < 0.8) {
          resetCharacter();
          break;
        }
      }

      // ★ 溶岩サバイバルゲーム処理 ★
      if (currentMode === 'lava' && lavaMesh) {
        lavaHeight += dt * 0.8;
        lavaMesh.position.y = lavaHeight;
        lavaTimer = Math.max(0, lavaTimer - dt);
        document.getElementById('lava-timer').textContent = `SURVIVE: ${Math.ceil(lavaTimer)}s`;

        if (player.y < lavaHeight + 0.2) {
          resetCharacter();
        }
        if (lavaTimer <= 0) {
          showCheckpointToast('🏆 SURVIVED THE LAVA! 完全勝利!');
          lavaTimer = 35;
          lavaHeight = -5;
        }
      }

      // ★ コイン集めゲーム処理 ★
      if (currentMode === 'pets') {
        for (let i = coinCollectibles.length - 1; i >= 0; i--) {
          const coin = coinCollectibles[i];
          coin.rotation.z += 0.04;
          if (Math.hypot(player.x - coin.position.x, player.z - coin.position.z) < 1.2) {
            scene.remove(coin);
            coinCollectibles.splice(i, 1);
            userCoins += 2;
            document.getElementById('pet-coin-count').textContent = userCoins;
          }
        }
      }

      // ★ お供ペットの追従アニメーション ★
      equippedPets.forEach((pet, idx) => {
        const angleOffset = (idx + 1) * 1.2;
        const targetX = player.x - Math.sin(player.rotation + angleOffset) * 1.2;
        const targetZ = player.z - Math.cos(player.rotation + angleOffset) * 1.2;
        pet.position.x += (targetX - pet.position.x) * 0.1;
        pet.position.z += (targetZ - pet.position.z) * 0.1;
        pet.position.y = player.y + 0.5 + Math.abs(Math.sin(now * 0.008 + idx)) * 0.25;
      });

      // 5. 奈落落下死判定
      if (player.y < -15) {
        resetCharacter();
      }

      // 6. チェックポイント通過判定
      for (const cp of checkpoints) {
        const d = Math.hypot(player.x - cp.x, player.z - cp.z);
        if (d < 1.4 && !cp.reached) {
          cp.reached = true;
          gameState.currentStage = cp.stage;
          gameState.checkpointPos.set(cp.x, cp.y, cp.z);
          cp.mesh.material.color.setHex(0x10b981);
          cp.mesh.material.emissive.setHex(0x059669);

          // HUD更新&トースト通知
          document.getElementById('top-stage-txt').textContent = `STAGE ${cp.stage} / ${gameState.maxStage}`;
          document.getElementById('lb-stage').textContent = `Stage ${cp.stage}`;
          showCheckpointToast(`STAGE ${cp.stage} CHECKPOINT REACHED!`);
        }
      }

      // 7. 星の回収判定
      for (let i = stars.length - 1; i >= 0; i--) {
        const s = stars[i];
        s.rotation.y += 0.03;
        if (Math.hypot(player.x - s.position.x, player.y - s.position.y, player.z - s.position.z) < 1.0) {
          scene.remove(s);
          stars.splice(i, 1);
          gameState.stars++;
          document.getElementById('hud-stars').textContent = gameState.stars;
        }
      }

      // 8. プレイヤーアニメーション & カメラ追従
      if (playerMesh) {
        playerMesh.position.set(player.x, player.y, player.z);
        playerMesh.rotation.y = player.rotation;

        if (avatar.isDancing) {
          // ダンスエモート
          playerMesh.position.y += Math.abs(Math.sin(now * 0.008)) * 0.2;
          playerMesh.rotation.y = Math.sin(now * 0.006) * 1.2;
          if (playerMesh.armLeft) playerMesh.armLeft.rotation.z = Math.sin(now * 0.01) * 1.2 - 0.5;
          if (playerMesh.armRight) playerMesh.armRight.rotation.z = -Math.sin(now * 0.01) * 1.2 + 0.5;
        } else if (len > 0 && player.isGrounded) {
          // 軽快な歩行アニメーション
          const swing = Math.sin(now * 0.018);
          if (playerMesh.armLeft) playerMesh.armLeft.rotation.x = swing * 0.6;
          if (playerMesh.armRight) playerMesh.armRight.rotation.x = -swing * 0.6;
          if (playerMesh.legLeft) playerMesh.legLeft.rotation.x = -swing * 0.7;
          if (playerMesh.legRight) playerMesh.legRight.rotation.x = swing * 0.7;
          playerMesh.position.y += Math.abs(swing) * 0.05;
        }
      }

      // カメラのスムーズ追従
      const targetCamX = player.x;
      const targetCamY = player.y + 3.4;
      const targetCamZ = player.z + 5.8;
      camera.position.x += (targetCamX - camera.position.x) * 0.12;
      camera.position.y += (targetCamY - camera.position.y) * 0.12;
      camera.position.z += (targetCamZ - camera.position.z) * 0.12;
      camera.lookAt(player.x, player.y + 0.9, player.z);

      // パーティクル更新
      for (let i = particles.length - 1; i >= 0; i--) {
        const p = particles[i];
        p.life -= dt;
        if (p.life <= 0) {
          scene.remove(p.mesh);
          particles.splice(i, 1);
          continue;
        }
        if (p.isRing) {
          p.mesh.scale.multiplyScalar(1.08);
          p.mesh.material.opacity = p.life / p.maxLife;
        } else {
          p.mesh.position.x += p.vx * dt;
          p.mesh.position.y += p.vy * dt;
          p.mesh.position.z += p.vz * dt;
          p.vy -= 12 * dt;
        }
      }

      renderer.render(scene, camera);
    }

    /* ----------------------------------------------------------
       UIアクション・操作入力・チャット
       ---------------------------------------------------------- */
    function setupInput() {
      window.addEventListener('keydown', e => {
        if (document.activeElement === document.getElementById('chat-input')) return;
        if (e.code === 'KeyW' || e.code === 'ArrowUp') keys.forward = true;
        if (e.code === 'KeyS' || e.code === 'ArrowDown') keys.backward = true;
        if (e.code === 'KeyA' || e.code === 'ArrowLeft') keys.left = true;
        if (e.code === 'KeyD' || e.code === 'ArrowRight') keys.right = true;
        if (e.code === 'ShiftLeft' || e.code === 'ShiftRight') keys.sprint = true;
        if (e.code === 'Space') { if (!e.repeat) triggerJump(); e.preventDefault(); }
        if (e.code === 'KeyR' && e.ctrlKey) resetCharacter();
        if (e.code === 'Escape') toggleRobloxMenu();
        if (e.code === 'Slash') {
          e.preventDefault();
          document.getElementById('chat-input').focus();
        }
      });

      window.addEventListener('keyup', e => {
        if (e.code === 'KeyW' || e.code === 'ArrowUp') keys.forward = false;
        if (e.code === 'KeyS' || e.code === 'ArrowDown') keys.backward = false;
        if (e.code === 'KeyA' || e.code === 'ArrowLeft') keys.left = false;
        if (e.code === 'KeyD' || e.code === 'ArrowRight') keys.right = false;
        if (e.code === 'ShiftLeft' || e.code === 'ShiftRight') keys.sprint = false;
      });

      // モバイルタッチボタン
      const bind = (id, key) => {
        const el = document.getElementById(id);
        if (!el) return;
        el.addEventListener('pointerdown', e => { e.preventDefault(); keys[key] = true; });
        el.addEventListener('pointerup', e => { e.preventDefault(); keys[key] = false; });
        el.addEventListener('pointerleave', e => { e.preventDefault(); keys[key] = false; });
      };
      bind('btn-up', 'forward'); bind('btn-down', 'backward'); bind('btn-left', 'left'); bind('btn-right', 'right'); bind('btn-sprint', 'sprint');
      const jmp = document.getElementById('btn-jump');
      if (jmp) jmp.addEventListener('pointerdown', e => { e.preventDefault(); triggerJump(); });
    }

    function toggleRobloxMenu() {
      const modal = document.getElementById('roblox-esc-modal');
      modal.classList.toggle('hidden');
      modal.classList.toggle('flex');
    }

    function toggleChatWindow() {
      document.getElementById('roblox-chat').classList.toggle('hidden');
    }

    function toggleLeaderboard() {
      document.getElementById('roblox-leaderboard').classList.toggle('hidden');
    }

    function triggerEmote(name) {
      if (name === 'dance') {
        avatar.isDancing = !avatar.isDancing;
        addChatMessage(`[Emote] /e dance を実行しました!🌸`);
      }
    }

    function handleChatSubmit(e) {
      e.preventDefault();
      const input = document.getElementById('chat-input');
      const msg = input.value.trim();
      if (!msg) return;

      addChatMessage(`<span class="text-pink-300 font-bold">[You]:</span> ${msg}`);
      if (msg.startsWith('/e dance')) {
        triggerEmote('dance');
      } else if (msg.startsWith('/re') || msg.startsWith('/reset')) {
        resetCharacter();
      }
      input.value = '';
      input.blur();
    }

    function addChatMessage(html) {
      const box = document.getElementById('chat-messages');
      const d = document.createElement('div');
      d.className = 'text-xs';
      d.innerHTML = html;
      box.appendChild(d);
      box.scrollTop = box.scrollHeight;
    }

    function showCheckpointToast(msg) {
      const t = document.getElementById('checkpoint-toast');
      document.getElementById('checkpoint-msg').textContent = msg;
      t.classList.remove('opacity-0', '-translate-y-10');
      setTimeout(() => {
        t.classList.add('opacity-0', '-translate-y-10');
      }, 2200);
    }

    // アバター工房ドロワーの開閉
    function openAvatarStudio() {
      document.getElementById('avatar-drawer').classList.remove('translate-x-full');
      renderCustomizerOptions();
    }

    function closeAvatarStudio() {
      document.getElementById('avatar-drawer').classList.add('translate-x-full');
      spawnPlayer(); // 新しいアバターでリスポーン
    }

    /* ----------------------------------------------------------
       アバターカスタマイザーUI描画
       ---------------------------------------------------------- */
    let activeCategory = 'face';

    function selectCategory(cat) {
      activeCategory = cat;
      document.querySelectorAll('.cat-tab').forEach(b => {
        b.className = 'cat-tab py-2.5 px-3 text-xs font-bold border-b-2 border-transparent text-slate-500 whitespace-nowrap';
      });
      const t = document.getElementById(`cat-${cat}`);
      if (t) t.className = 'cat-tab py-2.5 px-3 text-xs font-extrabold border-b-2 border-pink-500 text-pink-600 whitespace-nowrap';
      renderCustomizerOptions();
    }

    function renderCustomizerOptions() {
      const container = document.getElementById('customizer-options');
      if (!container) return;
      let html = '';

      if (activeCategory === 'face') {
        html = `
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">瞳のタイプ</label>
            <div class="grid grid-cols-3 gap-2">
              ${[
                { id: 'starry', label: '✨ うるうる星' },
                { id: 'heart', label: '💖 ハート目' },
                { id: 'cute', label: '🌸 まんまる' }
              ].map(opt => `
                <button onclick="updateAvatarProp('eyeType', '${opt.id}')" class="p-2 rounded-xl border text-xs font-bold ${avatar.eyeType === opt.id ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">
                  ${opt.label}
                </button>
              `).join('')}
            </div>
          </div>
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">アイパッチ (眼帯)</label>
            <div class="grid grid-cols-2 gap-2">
              <button onclick="updateAvatarProp('eyepatch', 'medical')" class="p-2 rounded-xl border text-xs font-bold ${avatar.eyepatch === 'medical' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">🩹 医療ガーゼ眼帯</button>
              <button onclick="updateAvatarProp('eyepatch', 'none')" class="p-2 rounded-xl border text-xs font-bold ${avatar.eyepatch === 'none' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">なし (両目)</button>
            </div>
          </div>
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">瞳の色</label>
            <div class="flex items-center gap-3">
              <input type="color" value="${avatar.eyeColor}" onchange="updateAvatarProp('eyeColor', this.value)" class="w-10 h-10 rounded-xl cursor-pointer">
              <div class="flex gap-1.5 flex-wrap">
                ${['#818cf8', '#f43f5e', '#06b6d4', '#10b981', '#f59e0b', '#1e293b'].map(c => `
                  <button onclick="updateAvatarProp('eyeColor', '${c}')" class="w-7 h-7 rounded-lg border-2 ${avatar.eyeColor === c ? 'border-pink-500 scale-110' : 'border-white'}" style="background:${c}"></button>
                `).join('')}
              </div>
            </div>
          </div>
        `;
      } else if (activeCategory === 'hair') {
        html = `
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">前髪のスタイル</label>
            <div class="grid grid-cols-3 gap-2 mb-3">
              <button onclick="updateAvatarProp('bangType', 'parted')" class="p-2 rounded-xl border text-xs font-bold ${avatar.bangType === 'parted' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">✨ ふんわり分け</button>
              <button onclick="updateAvatarProp('bangType', 'straight')" class="p-2 rounded-xl border text-xs font-bold ${avatar.bangType === 'straight' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">🎀 ぱっつん</button>
              <button onclick="updateAvatarProp('bangType', 'sideSwept')" class="p-2 rounded-xl border text-xs font-bold ${avatar.bangType === 'sideSwept' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">💫 横流し</button>
            </div>
          </div>
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">髪の色</label>
            <div class="flex items-center gap-3">
              <input type="color" value="${avatar.hairColor}" onchange="updateAvatarProp('hairColor', this.value)" class="w-10 h-10 rounded-xl cursor-pointer">
              <div class="flex gap-1.5 flex-wrap">
                ${['#e2e8f0', '#334155', '#fed7aa', '#fdf4ff', '#22d3ee', '#18181b', '#f43f5e', '#a855f7'].map(c => `
                  <button onclick="updateAvatarProp('hairColor', '${c}')" class="w-7 h-7 rounded-lg border-2 ${avatar.hairColor === c ? 'border-pink-500 scale-110' : 'border-white'}" style="background:${c}"></button>
                `).join('')}
              </div>
            </div>
          </div>
          <div class="pt-1">
            <label class="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" ${avatar.hasAhoge ? 'checked' : ''} onchange="updateAvatarProp('hasAhoge', this.checked)" class="w-4 h-4 text-pink-500 rounded">
              <span class="text-xs font-bold text-slate-700">ぴょこんと揺れるアホ毛をつける</span>
            </label>
          </div>
        `;
      } else if (activeCategory === 'clothes') {
        html = `
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">洋服のカラー</label>
            <div class="flex items-center gap-3">
              <input type="color" value="${avatar.topColor}" onchange="updateAvatarProp('topColor', this.value)" class="w-10 h-10 rounded-xl cursor-pointer">
              <div class="flex gap-1.5 flex-wrap">
                ${['#93c5fd', '#1e293b', '#fae8ff', '#fbcfe8', '#0f172a', '#10b981', '#ffffff'].map(c => `
                  <button onclick="updateAvatarProp('topColor', '${c}')" class="w-7 h-7 rounded-lg border-2 ${avatar.topColor === c ? 'border-pink-500 scale-110' : 'border-white'}" style="background:${c}"></button>
                `).join('')}
              </div>
            </div>
          </div>
          <div class="pt-2 flex items-center justify-between">
            <label class="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" ${avatar.hasSkirt ? 'checked' : ''} onchange="updateAvatarProp('hasSkirt', this.checked)" class="w-4 h-4 text-pink-500 rounded">
              <span class="text-xs font-bold text-slate-700">フリルプリーツスカート</span>
            </label>
            <input type="color" value="${avatar.skirtColor}" onchange="updateAvatarProp('skirtColor', this.value)" class="w-8 h-8 rounded-lg cursor-pointer">
          </div>
          <div class="pt-2 flex items-center justify-between">
            <label class="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" ${avatar.hasChestRibbon ? 'checked' : ''} onchange="updateAvatarProp('hasChestRibbon', this.checked)" class="w-4 h-4 text-pink-500 rounded">
              <span class="text-xs font-bold text-slate-700">胸元リボンチャーム</span>
            </label>
            <input type="color" value="${avatar.ribbonColor}" onchange="updateAvatarProp('ribbonColor', this.value)" class="w-8 h-8 rounded-lg cursor-pointer">
          </div>
        `;
      } else if (activeCategory === 'accessory') {
        html = `
          <div>
            <label class="block text-xs font-black text-slate-600 mb-2">頭部アクセサリー</label>
            <div class="grid grid-cols-2 gap-2">
              <button onclick="updateAvatarProp('headAcc', 'sunglasses')" class="p-2 rounded-xl border text-xs font-bold ${avatar.headAcc === 'sunglasses' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">🕶️ クリアサングラス</button>
              <button onclick="updateAvatarProp('headAcc', 'none')" class="p-2 rounded-xl border text-xs font-bold ${avatar.headAcc === 'none' ? 'border-pink-500 bg-pink-50 text-pink-600' : 'border-slate-200 bg-white'}">なし</button>
            </div>
          </div>
        `;
      } else if (activeCategory === 'body') {
        html = `
          <div class="space-y-3">
            <div>
              <div class="flex justify-between text-xs font-black text-slate-600 mb-1">
                <span>ウエストの細さ</span>
                <span>${Math.round(avatar.waistScale * 100)}%</span>
              </div>
              <input type="range" min="0.6" max="1.1" step="0.02" value="${avatar.waistScale}" oninput="updateAvatarProp('waistScale', parseFloat(this.value))" class="w-full accent-pink-500">
            </div>
            <div>
              <div class="flex justify-between text-xs font-black text-slate-600 mb-1">
                <span>頭の大きさ (チビ感)</span>
                <span>${Math.round(avatar.headScale * 100)}%</span>
              </div>
              <input type="range" min="0.8" max="1.3" step="0.02" value="${avatar.headScale}" oninput="updateAvatarProp('headScale', parseFloat(this.value))" class="w-full accent-pink-500">
            </div>
          </div>
        `;
      }

      container.innerHTML = html;
      lucide.createIcons();
    }

    function updateAvatarProp(prop, value) {
      avatar[prop] = value;
      spawnPlayer();
      renderCustomizerOptions();
    }

    function randomizeAvatar() {
      const colors = ['#93c5fd', '#fbcfe8', '#fed7aa', '#c7d2fe', '#a7f3d0', '#334155'];
      avatar.topColor = colors[Math.floor(Math.random() * colors.length)];
      avatar.eyeColor = colors[Math.floor(Math.random() * colors.length)];
      avatar.hairColor = ['#e2e8f0', '#334155', '#fdf4ff', '#fed7aa'][Math.floor(Math.random() * 4)];
      spawnPlayer();
      renderCustomizerOptions();
    }

    window.addEventListener('DOMContentLoaded', () => {
      lucide.createIcons();
      initRobloxWorld();
    });
  </script>
</body>
</html>

アバターアスレチック

by りい

すきなアバターをつくって、ゲームの世界で遊べるゲーム。 ジャンプはスペースキー、歩くのは十字キーです。

🤖 使用したAI
Gemini
👁 72 回閲覧
📅 投稿:2026年9月12日 🔄 更新:2026年11月14日
応援スタンプを押してみよう!