LoginSignup
10
6

More than 5 years have passed since last update.

WebVR A-frame で実現するぐるっと回り込むカメラ

Last updated at Posted at 2018-01-19

A-Frameという超簡単にWebGLが組めるフレームワークを今更ながら知ったのですが、カメラの挙動が欲しいのと違ったため、ちょっといじってみました。

A-Frameとは

WebGLを扱うThree.jsをベースに開発されたフレームワークで、ざっくり言うとブラウザ上にVR空間を作ることができます。

公式
https://aframe.io/
とてもわかりやすい記事
https://qiita.com/haruan2394/items/a2d54101377b96ba08f2

ぐるっとまわりこむカメラやりたい!

上記の記事のサンプルなどではカメラはWASDで移動できるわけですが、自分が欲しかったのは空間の中心にあるオブジェクトの方を見ながらその周りをまわるようなカメラワークでした。ようするにアニメの「サマーウォーズ」のOZとか「攻殻機動隊」の電脳空間みたいなのがやりたかったわけですね。

見つけられてないだけかもしれませんが、サンプルがなかったので自分で作ってみました。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>A-Frame</title>
    <meta name="description" content="A-Frame Panorama Sample">
    <script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene vr-mode-ui="enabled: false">
        <a-box color="tomato" position="0 0 0" position="0 0 0" depth="2" height="2" width="2" id="moon"></a-box>
        <a-box color="tomato" position="0 1 1" position="0 0 0" depth="1" height="1" width="1" id="moon"></a-box>

        <a-camera position="0 0 10" rotation="0 0 0" camera="userHeight: 0" id="camera">
            <a-ring color="teal" position="0 0 -1" radius-inner="0.05" radius-outer="0.07"></a-ring>
        </a-camera>
    <a-sky src="t.png" rotation="0 170 0"></a-sky>
    </a-scene>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
    <script>
        let camera_length=10;
        let camera_theata=0;

        //IE11用
        (function () {
          if ( typeof window.CustomEvent === "function" ) return false;
          function CustomEvent ( event, params ) {
            params = params || { bubbles: false, cancelable: false, detail: undefined };
            var evt = document.createEvent( 'CustomEvent' );
            evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
            return evt;
           }
          CustomEvent.prototype = window.Event.prototype;
          window.CustomEvent = CustomEvent;
        })();

        //ぐるっとまわりこませる
        $(window).keydown(function(e){
          if(e.keyCode==88){//x
            camera_theata++;
            $("#camera").attr("position",camera_length*Math.sin(camera_theata*Math.PI/180)+" 0 "+camera_length*Math.cos(camera_theata*Math.PI/180));
            $("#camera").attr("rotation","0 "+camera_theata+" 0");
          }
        });
    </script>
  </body>
</html>

t.pngはこちらの1200x600画像を使いました。ご自由にお使いください。
t.png

こちらでxキーを押すと原点に設置されたキューブの周りをまわるようになります。原理はいたって単純で、三角関数で原点周りを移動しながらカメラの向きを変えて原点を常に見ている状態にしています。ここら辺はLookAtつかったほうがいいかもしれません。なお原点からの距離はcamera_lengthで調整してください。

10
6
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
10
6