LoginSignup
13
12

More than 5 years have passed since last update.

three.jsで作った空間をJavascriptでビューんと飛ぶ。

Last updated at Posted at 2016-07-15

つまりは、three.js editorで作った3D空間のカメラの座標を Javascriptで動かして、視点を動かしてみよう。というお話です。

まず、three.js/editor を使ってテスト用の3D空間を作成。
(と言ってもまずは簡単なオブジェクトを置いただけの空間を作成)
立方体とか円柱とか球とか単純なオブジェクトなら、サクサクと配置可能

そして、File - Export Scene を選択して、JSONでエクスポートします。
スクリーンショット 2016-07-13 9.49.17.png

スクリーンショット 2016-07-13 9.49.23.png

エクスポートすると「scene.json」がダウンロードされます。
出来上がったJSONを読み込めるようにします。
https://github.com/motokazu/threejs-playroom/blob/master/json/scene.json

サンプルコード:
https://github.com/motokazu/threejs-playroom

$ git clone https://github.com/motokazu/threejs-playroom.git
$ cd threejs-playroom
$ python -m SimpleHTTPServer 8080

index.htmlのあるディレクトリで http サーバーを起動して、ブラウザを開いて http://localhost:8080 にアクセスします。

カメラを動かすところは、room.js の L47-L59です。

// target object
var targetLookAt = new THREE.Vector3( 0, 0, 0 );

function animate(){
    requestAnimationFrame(animate);
    renderer.render(scene, camera);

    if(cameraWorks && cameraWorks.length > 0){
        var pos = cameraWorks.shift();
        camera.position.x = pos.x;
        camera.position.y = pos.y;
        camera.position.z = pos.z;

        camera.lookAt( targetLookAt );
    }
}

(x,y,z) = (0,0,0) を見ながら カメラが指定した座標を移動します。

このサンプルでは、移動させる座標は cameraWorks 配列に入っています。

// camera work
var cameraWorks = [];
for(var i = 0;i < 10000; i++ ){
    var p = {};
    p.x = Math.sin(i/100)*20;
    p.y = Math.sin(i/100)*10+20;
    p.z = Math.cos(i/100)*20;

    cameraWorks.push(p);
}

ぐるぐると動きます。

13
12
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
13
12