mcpField
A
aframe-webxr

aframe-webxr

github.com/freshtechbro開発1.2k2.4k 回インストール49 週間前に更新
リポジトリ

aframe-webxr について

aframe-webxrは、A-Frameでブラウザー向けのVR・AR体験を構築するスキルです。WebXR開発者向けに、宣言的な3Dシーンや操作方法を紹介し、デスクトップ、モバイル、ヘッドセットでの開発を扱います。

主な機能

  1. 01HTMLによる宣言的な3Dシーン
  2. 02エンティティ・コンポーネント・システムの概念
  3. 03VRコントローラーと視線操作
  4. 04ARヒットテストのパターン
  5. 05カスタムコンポーネントの解説
  6. 06シーンのパフォーマンス実践

活用シーン

  1. 01HTMLプリミティブで3Dシーンを試作
  2. 02VR体験にコントローラー操作を追加
  3. 03ARで検出した面に仮想オブジェクトを配置
  4. 04360度画像や動画の体験を構築

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/freshtechbro/claudedesignskills --skill aframe-webxr

インストール後、Claude Code で/aframe-webxrを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

assets/examples/
README.md
assets/starter_aframe/
index.html
main.js
README.md
style.css
references/
api_reference.md
components_library.md
webxr_guide.md
scripts/
component_builder.py
scene_generator.py

詳細

A-Frame WebXR スキル

このスキルを使う場面

  • 最小限の JavaScript で VR/AR 体験を構築する
  • クロスプラットフォームの WebXR アプリケーション(デスクトップ、モバイル、ヘッドセット)を作成する
  • HTML プリミティブを使って 3D シーンを素早くプロトタイプする
  • VR コントローラーの操作を実装する
  • 宣言的な方法でウェブページに 3D コンテンツを追加する
  • 360° 画像/動画の体験を構築する
  • ヒットテストを使った AR 体験を開発する

コア概念

1. エンティティ・コンポーネント・システム(ECS)

A-Frame は、以下の要素からなるエンティティ・コンポーネント・システムのアーキテクチャを採用しています。

  • エンティティはコンテナーです(HTML の <div> のようなものです)。
  • コンポーネントはエンティティに機能や外観を追加します。
  • システムはグローバルな機能を提供します。

<a-entity
  geometry="primitive: box; width: 2"
  material="color: red; metalness: 0.5"
  position="0 1.5 -3"
  rotation="0 45 0">
</a-entity>

プリミティブは、よく使うエンティティとコンポーネントの組み合わせを簡潔に記述する方法です。


<a-box color="red" position="0 1.5 -3" rotation="0 45 0" width="2"></a-box>


<a-entity
  geometry="primitive: box; width: 2"
  material="color: red"
  position="0 1.5 -3"
  rotation="0 45 0">
</a-entity>
2. シーンの設定

A-Frame アプリはすべて <a-scene> から始まります。

<!DOCTYPE html>
<html>
  <head>
    <script src="https://aframe.io/releases/1.7.1/aframe.min.js"></script>
  </head>
  <body>
    <a-scene>
      
      <a-box position="-1 0.5 -3" color="#4CC3D9"></a-box>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
      <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    </a-scene>
  </body>
</html>

シーンには次の要素が自動的に追加されます。

  • デフォルトカメラ(位置:0 1.6 0)
  • 視点コントロール(マウスドラッグ)
  • WASD コントロール(キーボード操作)
3. カメラシステム

デフォルトカメラ(指定されていない場合に自動で追加されます):

<a-entity camera="active: true" look-controls wasd-controls position="0 1.6 0"></a-entity>

カスタムカメラ:

<a-camera position="0 2 5" look-controls wasd-controls="acceleration: 50"></a-camera>

カメラリグ(移動と回転を個別に行う場合):

<a-entity id="rig" position="0 0 0">
  
  <a-camera look-controls></a-camera>

  
</a-entity>

コントローラー付き VR カメラリグ:

<a-entity id="rig" position="0 0 0">
  
  <a-camera position="0 1.6 0"></a-camera>

  
  <a-entity
    hand-controls="hand: left"
    laser-controls="hand: left">
  </a-entity>

  
  <a-entity
    hand-controls="hand: right"
    laser-controls="hand: right">
  </a-entity>
</a-entity>
4. ライティング

環境光(グローバルイルミネーション):

<a-entity light="type: ambient; color: #BBB; intensity: 0.5"></a-entity>

指向性ライト(太陽光のような光):

<a-entity light="type: directional; color: #FFF; intensity: 0.8" position="1 2 1"></a-entity>

ポイントライト(全方向に放射される光):

<a-entity light="type: point; color: #F00; intensity: 2; distance: 50" position="0 3 0"></a-entity>

スポットライト(円錐状の光束):

<a-entity light="type: spot; angle: 45; intensity: 1.5" position="0 5 0" rotation="-90 0 0"></a-entity>
5. マテリアルとテクスチャ

スタンダードマテリアル:

<a-sphere
  material="color: #FF0000; metalness: 0.5; roughness: 0.3"
  position="0 1 -3">
</a-sphere>

テクスチャ付きマテリアル:

<a-assets>
  <img id="woodTexture" src="wood.jpg">
</a-assets>

<a-box material="src: #woodTexture" position="0 1 -3"></a-box>

フラットシェーディング(ライティングなし):

<a-plane material="shader: flat; color: #4CC3D9"></a-plane>
6. アニメーション

プロパティアニメーション:

<a-box
  position="0 1 -3"
  animation="property: rotation; to: 0 360 0; loop: true; dur: 5000">
</a-box>

複数のアニメーション(animation__* 形式の名前を使用):

<a-sphere
  position="0 1 -3"
  animation__position="property: position; to: 0 3 -3; dir: alternate; loop: true; dur: 2000"
  animation__rotation="property: rotation; to: 360 360 0; loop: true; dur: 4000"
  animation__scale="property: scale; to: 1.5 1.5 1.5; dir: alternate; loop: true; dur: 1000">
</a-sphere>

イベントベースのアニメーション:

<a-box
  color="blue"
  animation__mouseenter="property: scale; to: 1.2 1.2 1.2; startEvents: mouseenter"
  animation__mouseleave="property: scale; to: 1 1 1; startEvents: mouseleave"
  animation__click="property: rotation; from: 0 0 0; to: 0 360 0; startEvents: click">
</a-box>
7. アセット管理

パフォーマンスを向上させるため、アセットを事前に読み込みます。

<a-scene>
  <a-assets>
    
    <img id="texture1" src="texture.jpg">
    <img id="skyTexture" src="sky.jpg">

    
    <video id="video360" src="360video.mp4" autoplay loop></video>

    
    <audio id="bgMusic" src="music.mp3" preload="auto"></audio>

    
    <a-asset-item id="tree" src="tree.gltf"></a-asset-item>

    
    <a-mixin id="redMaterial" material="color: red; metalness: 0.7"></a-mixin>
  </a-assets>

  
  <a-entity gltf-model="#tree" position="2 0 -5"></a-entity>
  <a-sphere mixin="redMaterial" position="0 1 -3"></a-sphere>
  <a-sky src="#skyTexture"></a-sky>
</a-scene>
8. カスタムコンポーネント

ロジックをカプセル化するカスタムコンポーネントを登録します。

AFRAME.registerComponent('rotate-on-click', {
  // Component schema (configuration)
  schema: {
    speed: {type: 'number', default: 1}
  },

  // Lifecycle: called once when component attached
  init: function() {
    this.el.addEventListener('click', () => {
      this.rotating = !this.rotating;
    });
  },

  // Lifecycle: called every frame
  tick: function(time, timeDelta) {
    if (this.rotating) {
      var rotation = this.el.getAttribute('rotation');
      rotation.y += this.data.speed;
      this.el.setAttribute('rotation', rotation);
    }
  }
});
<a-box rotate-on-click="speed: 2" position="0 1 -3"></a-box>

よくあるパターン

パターン 1:VR コントローラーの操作

課題:VR でオブジェクトをつかんで操作できるようにする

解決策:hand-controls とカスタム grab コンポーネントを使用します。

<a-scene>
  
  <a-entity id="rig">
    <a-camera position="0 1.6 0"></a-camera>

    <a-entity
      id="leftHand"
      hand-controls="hand: left"
      laser-controls="hand: left">
    </a-entity>

    <a-entity
      id="rightHand"
      hand-controls="hand: right"
      laser-controls="hand: right">
    </a-entity>
  </a-entity>

  
  <a-box class="grabbable" position="-1 1.5 -3" color="#4CC3D9"></a-box>
  <a-sphere class="grabbable" position="1 1.5 -3" color="#EF2D5E"></a-sphere>
</a-scene>

<script>
AFRAME.registerComponent('grabbable', {
  init: function() {
    var el = this.el;

    el.addEventListener('triggerdown', function(evt) {
      console.log('Grabbed by', evt.detail.hand);
      el.setAttribute('color', 'green');
    });

    el.addEventListener('triggerup', function(evt) {
      el.setAttribute('color', 'blue');
    });

    el.addEventListener('gripdown', function(evt) {
      // Attach object to controller
      var controllerEl = evt.detail.controller;
      controllerEl.object3D.attach(el.object3D);
    });

    el.addEventListener('gripup', function(evt) {
      // Detach from controller
      var sceneEl = el.sceneEl.object3D;
      sceneEl.attach(el.object3D);
    });
  }
});

// Apply grabbable component
document.querySelectorAll('.grabbable').forEach(el => {
  el.setAttribute('grabbable', '');
});
</script>
パターン 2:360° 画像ギャラリー

課題:インタラクティブな 360° フォトビューアーを作成する

解決策:sky プリミティブとクリック可能なサムネイルを使用します。

<a-scene>
  <a-assets>
    <img id="city" src="city.jpg">
    <img id="forest" src="forest.jpg">
    <img id="beach" src="beach.jpg">
    <img id="city-thumb" src="city-thumb.jpg">
    <img id="forest-thumb" src="forest-thumb.jpg">
    <img id="beach-thumb" src="beach-thumb.jpg">
    <audio id="click-sound" src="click.mp3"></audio>
  </a-assets>

  
  <a-sky id="image-360" src="#city" rotation="0 -130 0"></a-sky>

  
  <a-entity id="menu" position="0 1.6 -2">
    <a-entity class="link"
      geometry="primitive: plane; width: 0.7; height: 0.7"
      material="shader: flat; src: #city-thumb"
      position="-1 0 0"
      sound="on: click; src: #click-sound"
      event-set__mouseenter="scale: 1.2 1.2 1"
      event-set__mouseleave="scale: 1 1 1"
      event-set__click="_target: #image-360; material.src: #city">
    </a-entity>

    <a-entity class="link"
      geometry="primitive: plane; width: 0.7; height: 0.7"
      material="shader: flat; src: #forest-thumb"
      position="0 0 0"
      sound="on: click; src: #click-sound"
      event-set__mouseenter="scale: 1.2 1.2 1"
      event-set__mouseleave="scale: 1 1 1"
      event-set__click="_target: #image-360; material.src: #forest">
    </a-entity>

    <a-entity class="link"
      geometry="primitive: plane; width: 0.7; height: 0.7"
      material="shader: flat; src: #beach-thumb"
      position="1 0 0"
      sound="on: click; src: #click-sound"
      event-set__mouseenter="scale: 1.2 1.2 1"
      event-set__mouseleave="scale: 1 1 1"
      event-set__click="_target: #image-360; material.src: #beach">
    </a-entity>
  </a-entity>

  
  <a-camera>
    <a-cursor raycaster="objects: .link"></a-cursor>
  </a-camera>
</a-scene>
パターン 3:AR ヒットテスト(現実世界にオブジェクトを配置する)

課題:検出した現実世界の表面に仮想オブジェクトを配置する

解決策:ar-hit-test コンポーネントを使用します。

<a-scene
  webxr="optionalFeatures: hit-test, dom-overlay; overlayElement: #overlay"
  ar-hit-test="target: #furniture; type: footprint">

  <a-assets>
    <a-asset-item id="chair" src="chair.gltf"></a-asset-item>
  </a-assets>

  
  <a-entity id="furniture" gltf-model="#chair" scale="0.5 0.5 0.5"></a-entity>

  
  <div id="overlay" style="position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
                           background: rgba(0,0,0,0.7); color: white; padding: 15px;
                           border-radius: 8px; font-family: sans-serif;">
    <p id="message">Tap to enter AR mode</p>
  </div>
</a-scene>

<script>
const sceneEl = document.querySelector('a-scene');
const message = document.getElementById('message');

sceneEl.addEventListener('enter-vr', function() {
  if (this.is('ar-mode')) {
    message.textContent = '';

    this.addEventListener('ar-hit-test-start', function() {
      message.innerHTML = 'Scanning environment, finding surface.';
    }, { once: true });

    this.addEventListener('ar-hit-test-achieved', function() {
      message.innerHTML = 'Tap on the screen to place the object.';
    }, { once: true });

    this.addEventListener('ar-hit-test-select', function() {
      message.textContent = 'Object placed!';
      setTimeout(() => message.textContent = '', 2000);
    }, { once: true });
  }
});

sceneEl.addEventListener('exit-vr', function() {
  message.textContent = 'Tap to enter AR mode';
});
</script>
パターン 4:マウス/視線による操作

課題:デスクトップのマウスや VR の視線でクリック操作できるようにする

解決策:cursor コンポーネントと raycaster を使用します。

<a-scene>
  
  <a-box
    class="interactive"
    position="-1 1.5 -3"
    color="#4CC3D9"
    event-set__mouseenter="color: yellow"
    event-set__mouseleave="color: #4CC3D9"
    event-set__click="scale: 1.5 1.5 1.5">
  </a-box>

  <a-sphere
    class="interactive"
    position="1 1.5 -3"
    color="#EF2D5E"
    event-set__click="color: orange; scale: 2 2 2">
  </a-sphere>

  <a-plane position="0 0 -4" rotation="-90 0 0" width="10" height="10" color="#7BC8A4"></a-plane>

  
  <a-camera position="0 1.6 0">
    
    <a-cursor
      raycaster="objects: .interactive"
      fuse="true"
      fuse-timeout="1500">
    </a-cursor>
  </a-camera>
</a-scene>

<script>
// Advanced click handling with JavaScript
document.querySelectorAll('.interactive').forEach(el => {
  el.addEventListener('click', function(evt) {
    console.log('Clicked:', this.id || this.tagName);
    console.log('Intersection point:', evt.detail.intersection.point);
  });
});
</script>
パターン 5:動的なシーン生成

課題:プログラムからエンティティを作成して操作する

解決策:JavaScript の DOM 操作を使用します。

<a-scene>
  <a-camera position="0 1.6 5"></a-camera>
  <a-entity light="type: ambient; color: #888"></a-entity>
  <a-entity light="type: directional; color: #FFF" position="1 2 1"></a-entity>
</a-scene>

<script>
const scene = document.querySelector('a-scene');

// Create sphere
function createSphere(x, y, z, color) {
  const entity = document.createElement('a-entity');

  entity.setAttribute('geometry', {
    primitive: 'sphere',
    radius: 0.5
  });

  entity.setAttribute('material', {
    color: color,
    metalness: 0.5,
    roughness: 0.3
  });

  entity.setAttribute('position', {x, y, z});

  // Add animation
  entity.setAttribute('animation', {
    property: 'position',
    to: `${x} ${y + 1} ${z}`,
    dir: 'alternate',
    loop: true,
    dur: 2000
  });

  scene.appendChild(entity);
  return entity;
}

// Generate grid of spheres
for (let x = -3; x <= 3; x += 1.5) {
  for (let z = -5; z <= -2; z += 1.5) {
    const color = `#${Math.floor(Math.random()*16777215).toString(16)}`;
    createSphere(x, 1, z, color);
  }
}

// Listen to component changes
scene.addEventListener('componentchanged', function(evt) {
  console.log('Component changed:', evt.detail.name);
});

// Access Three.js objects directly
setTimeout(() => {
  const entities = document.querySelectorAll('a-entity[geometry]');
  entities.forEach(el => {
    el.object3D.visible = true; // Direct Three.js manipulation
  });
}, 1000);
</script>
パターン 6:環境とスカイボックス

課題:没入感のある環境を素早く作成する

解決策:コミュニティ製コンポーネントと 360° 画像を使用します。

<html>
  <head>
    <script src="https://aframe.io/releases/1.7.1/aframe.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@fern-solutions/aframe-sky-background/dist/sky-background.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/c-frame/[email protected]/dist/aframe-extras.min.js"></script>
  </head>
  <body>
    <a-scene>
      
      <a-sky-background
        top-color="#4A90E2"
        bottom-color="#87CEEB">
      </a-sky-background>

      
      

      
      <a-entity
        ocean="density: 20; width: 50; depth: 50; speed: 4"
        material="color: #9CE3F9; opacity: 0.75; metalness: 0; roughness: 1"
        rotation="-90 0 0">
      </a-entity>

      
      <a-entity
        particle-system="preset: snow; particleCount: 2000; color: #FFF">
      </a-entity>

      <a-entity light="type: ambient; color: #888"></a-entity>
      <a-entity light="type: directional; color: #FFF; intensity: 0.7" position="1 2 1"></a-entity>
    </a-scene>
  </body>
</html>
パターン 7:GLTF モデルの読み込み

課題:3D モデルを読み込んで表示する

解決策:アセット管理と gltf-model コンポーネントを使用します。

<a-scene>
  <a-assets>
    <a-asset-item id="robot" src="robot.gltf"></a-asset-item>
    <a-asset-item id="building" src="building.glb"></a-asset-item>
  </a-assets>

  
  <a-entity
    gltf-model="#robot"
    position="0 0 -3"
    scale="0.5 0.5 0.5"
    animation="property: rotation; to: 0 360 0; loop: true; dur: 10000">
  </a-entity>

  
  <a-entity
    gltf-model="#building"
    position="5 0 -10"
    animation-mixer="clip: *; loop: repeat">
  </a-entity>

  <a-camera position="0 1.6 5"></a-camera>
  <a-entity light="type: ambient; intensity: 0.5"></a-entity>
  <a-entity light="type: directional; intensity: 0.8" position="2 4 2"></a-entity>
</a-scene>

<script>
// Handle model loading events
document.querySelector('[gltf-model="#robot"]').addEventListener('model-loaded', (evt) => {
  console.log('Model loaded:', evt.detail.model);

  // Access Three.js object
  const model = evt.detail.model;
  model.traverse(node => {
    if (node.isMesh) {
      console.log('Mesh found:', node.name);
    }
  });
});

document.querySelector('[gltf-model="#robot"]').addEventListener('model-error', (evt) => {
  console.error('Model loading error:', evt.detail);
});
</script>

統合パターン

Three.js との連携

基盤となる Three.js オブジェクトにアクセスします。

// Get Three.js scene
const scene = document.querySelector('a-scene').object3D;

// Get entity's Three.js object
const box = document.querySelector('a-box');
const threeObject = box.object3D;

// Direct Three.js manipulation
threeObject.position.set(1, 2, 3);
threeObject.rotation.y = Math.PI / 4;

// Add custom Three.js objects
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
GSAP との連携(アニメーション)

GSAP で A-Frame のエンティティをアニメーションさせます。

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script>
const box = document.querySelector('a-box');

// Animate position
gsap.to(box.object3D.position, {
  x: 3,
  y: 2,
  z: -5,
  duration: 2,
  ease: 'power2.inOut'
});

// Animate rotation
gsap.to(box.object3D.rotation, {
  y: Math.PI * 2,
  duration: 3,
  repeat: -1,
  ease: 'none'
});

// Animate attributes
gsap.to(box.components.material.material, {
  opacity: 0.5,
  duration: 1
});
</script>
React との連携

React コンポーネントに A-Frame を組み込みます。

import React, { useEffect, useRef } from 'react';
import 'aframe';

function VRScene() {
  const sceneRef = useRef(null);

  useEffect(() => {
    const scene = sceneRef.current;

    // Create entities dynamically
    const entity = document.createElement('a-sphere');
    entity.setAttribute('position', '0 1.5 -3');
    entity.setAttribute('color', '#EF2D5E');
    scene.appendChild(entity);

    // Listen to events
    scene.addEventListener('enter-vr', () => {
      console.log('Entered VR mode');
    });
  }, []);

  return (
    <a-scene ref={sceneRef}>
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" />
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E" />
      <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D" />
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" />
      <a-sky color="#ECECEC" />
    </a-scene>
  );
}

export default VRScene;

パフォーマンスに関するベストプラクティス

1. アセット管理を使用する

処理をブロックしないよう、アセットを事前に読み込みます。

<a-assets>
  <img id="texture1" src="large-texture.jpg">
  <video id="video360" src="360video.mp4" preload="auto"></video>
  <a-asset-item id="model" src="complex-model.gltf"></a-asset-item>
</a-assets>
2. エンティティをプールする

エンティティを作成・破棄する代わりに再利用します。

AFRAME.registerComponent('bullet-pool', {
  init: function() {
    this.pool = [];
    this.used = [];

    // Pre-create bullets
    for (let i = 0; i < 20; i++) {
      const bullet = document.createElement('a-sphere');
      bullet.setAttribute('radius', 0.1);
      bullet.setAttribute('visible', false);
      this.el.sceneEl.appendChild(bullet);
      this.pool.push(bullet);
    }
  },

  getBullet: function() {
    if (this.pool.length > 0) {
      const bullet = this.pool.pop();
      bullet.setAttribute('visible', true);
      this.used.push(bullet);
      return bullet;
    }
  },

  returnBullet: function(bullet) {
    bullet.setAttribute('visible', false);
    const index = this.used.indexOf(bullet);
    if (index > -1) {
      this.used.splice(index, 1);
      this.pool.push(bullet);
    }
  }
});
3. ジオメトリを最適化する

ローポリモデルと LOD を使用します。


<a-sphere radius="1" segments-width="8" segments-height="6"></a-sphere>


<a-sphere radius="1" segments-width="32" segments-height="32"></a-sphere>
4. ドローコールを制限する

同じオブジェクトを繰り返し使う場合はインスタンシングを使用します。

AFRAME.registerComponent('instanced-trees', {
  init: function() {
    // Use Three.js InstancedMesh for repeated geometry
    const scene = this.el.sceneEl.object3D;
    const geometry = new THREE.ConeGeometry(0.5, 2, 8);
    const material = new THREE.MeshStandardMaterial({ color: 0x228B22 });
    const mesh = new THREE.InstancedMesh(geometry, material, 100);

    // Position instances
    for (let i = 0; i < 100; i++) {
      const matrix = new THREE.Matrix4();
      matrix.setPosition(
        Math.random() * 20 - 10,
        0,
        Math.random() * 20 - 10
      );
      mesh.setMatrixAt(i, matrix);
    }

    scene.add(mesh);
  }
});
5. tick() 関数を間引く

必要がなければ毎フレーム更新しないようにします。

AFRAME.registerComponent('throttled-update', {
  init: function() {
    this.lastUpdate = 0;
    this.updateInterval = 100; // ms
  },

  tick: function(time, timeDelta) {
    if (time - this.lastUpdate >= this.updateInterval) {
      // Expensive operation here
      this.lastUpdate = time;
    }
  }
});
6. 監視に Stats コンポーネントを使用する
<a-scene stats>
  
</a-scene>

よくある落とし穴と解決策

落とし穴 1:エンティティが表示されない

問題:追加したエンティティが表示されない

原因:

  • エンティティがカメラの背後に配置されている
  • スケールが 0 または非常に小さい
  • マテリアルの不透明度が 0
  • エンティティがカメラの視錐台の外側にある

解決策:

// Wait for scene to load
const scene = document.querySelector('a-scene');
scene.addEventListener('loaded', () => {
  const entity = document.createElement('a-box');
  entity.setAttribute('position', '0 1.5 -3'); // In front of camera
  entity.setAttribute('color', 'red');
  scene.appendChild(entity);
});

// Debug: Check entity position
console.log(entity.getAttribute('position'));

// Debug: Check if entity is in scene
console.log(entity.parentNode); // Should be <a-scene>
落とし穴 2:イベントが発生しない

問題:クリック/mouseenter イベントがトリガーされない

原因:レイキャスターまたはカーソルが設定されていない

解決策:


<a-camera>
  <a-cursor raycaster="objects: .interactive"></a-cursor>
</a-camera>


<a-box class="interactive" position="0 1 -3"></a-box>


<a-entity raycaster="objects: [geometry]" cursor></a-entity>
落とし穴 3:パフォーマンスの低下

問題:エンティティが多いと FPS が低下する

原因:

  • ドローコールが多すぎる
  • ジオメトリが複雑
  • テクスチャが最適化されていない
  • tick() の更新が多すぎる

解決策:

// 1. Use object pooling (see Performance section)
// 2. Simplify geometry
// 3. Optimize textures (reduce size, use compression)
// 4. Throttle updates

AFRAME.registerComponent('optimize-far-entities', {
  tick: function() {
    const camera = this.el.sceneEl.camera;
    const entities = document.querySelectorAll('[geometry]');

    entities.forEach(el => {
      const distance = el.object3D.position.distanceTo(camera.position);

      // Hide distant entities
      el.object3D.visible = distance < 50;
    });
  }
});
落とし穴 4:Zファイティング(サーフェスの重なり)

問題:サーフェスが重なるとちらつく

原因:2 つのサーフェスが同じ位置にある

解決策:


<a-plane position="0 0.01 0" rotation="-90 0 0"></a-plane>
<a-plane position="0 0.02 0" rotation="-90 0 0"></a-plane>


<a-entity
  geometry="primitive: plane"
  material="src: #texture1; transparent: true"
  class="has-render-order">
</a-entity>

<script>
document.querySelector('.has-render-order').object3D.renderOrder = 1;
</script>
落とし穴 5:モバイル VR のパフォーマンス

問題:モバイル VR でパフォーマンスが低い

解決策:


<a-scene renderer="maxCanvasWidth: 1920; maxCanvasHeight: 1920">


<a-sphere radius="1" segments-width="8" segments-height="6"></a-sphere>


<a-entity light="type: ambient; intensity: 0.6"></a-entity>
<a-entity light="type: directional; intensity: 0.4" position="1 2 1"></a-entity>


<a-scene renderer="antialias: false">
</a-scene>
落とし穴 6:アセットの読み込みに関する問題

問題:アセットが読み込まれない、または CORS エラーが発生する

解決策:


<a-assets>
  <img id="texture" src="https://example.com/texture.jpg" crossorigin="anonymous">
</a-assets>


<script>
const assets = document.querySelector('a-assets');
assets.addEventListener('loaded', () => {
  console.log('All assets loaded');
  // Safe to use assets now
});

assets.addEventListener('timeout', () => {
  console.error('Asset loading timeout');
});
</script>


<script>
const img = document.querySelector('img#texture');
img.addEventListener('error', () => {
  console.error('Failed to load texture');
  // Use fallback
  img.src = 'fallback-texture.jpg';
});
</script>

リソース

関連スキル

  • threejs-webgl:A-Frame の宣言型 API を超える高度な Three.js 制御向け
  • babylonjs-engine:異なるアーキテクチャを持つ代替 3D エンジン
  • gsap-scrolltrigger:GSAP で A-Frame エンティティをアニメーション化する場合
  • react-three-fiber:Three.js の React アプローチ(A-Frame の HTML アプローチとの比較)

コメント