4
5

More than 3 years have passed since last update.

【A-Frame】イベントをトリガーにしてanimationをスタートさせる【startEvents / emit】

Last updated at Posted at 2020-11-13

やること

WebVRを簡単に実装する A-Frame を使った開発で、
animationのスタートに トリガー を持たせたいときの方法をまとめます。

実装

0. a-sceneを用意

ベースの部分はA-FrameのIntroductionをご参照ください。
https://aframe.io/docs/1.0.0/introduction/

1. animationさせたいオブジェクトを用意

index.html
<a-scene vr-mode-ui="enabled: false">
  <a-sky color="skyblue"></a-sky>
  <a-box
    id="box"
    position="0 0 -5"
    color="white"
    animation="property: rotation; from: 0 0 0; to: 0 360 360; dur: 3000; loop: true; easing: linear;"
  ></a-box>
  <a-entity camera></a-entity>
</a-scene>

今回は白いboxを用意して、これを回転させるanimationを付けます。

スクリーンショット 2020-11-13 19.36.28.png

2. animationにstartEventsを追加

animationプロパティの中にstartEventsを追加します。

index.html
animation="property: rotation; from: 0 0 0; to: 0 360 360; dur: 3000; loop: true; easing: linear; startEvents: btnPush"

一番後ろの startEvents: btnPush の部分ですね。
イベント名(うしろ部分)は任意のもので大丈夫ですが、今回はボタンpushをトリガーとするため「btnPush」とします。

ちなみにこのstartEventsを入れるとanimationが勝手に再生されなくなります。

3. トリガーを用意

今回はボタンUIを押した時にanimationをスタートさせるようにするため、ボタンを用意します。

スクリーンショット 2020-11-13 19.38.40.png

body内に🍰のボタンを用意しました。

index.html
<button id="btn" class="btn">🍰</button>

併せてJS側でボタンのクリックイベントを用意します。

index.js
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
  console.log("click!");
});

4. JSでイベントを記述

以下のようにanimationのついたオブジェクトに対して、.emit("イベント名")とすることで
任意のタイミングでanimationをスタートさせることができます。

index.js
const box = document.getElementById("box");
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
  box.emit("btnPush");
});

box.emit("btnPush");の部分です。

これでボタンを押した時にboxのanimationをスタートすることができました。

giphy.gif

あと一時停止するイベント pauseEvents もあるようなのでまた気が向いたらその辺も追記します。

ドキュメント

A-Frame - animation
https://aframe.io/docs/1.0.0/components/animation.html#sidebar

動作環境

PC chrome
A-Frame v1.0.4

余談

A-Frameの古いバージョンでは startsEvents ではなく begin という名称でした。
最新のバージョンでbeginが動かない!
古いバージョンでstartsEventsが動かない!
というときは名称を変えるかバージョンを変えるかしてお試しください。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5