Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add datgui controls for camera in threejs?

I want to to enable dat-gui controls for the threejs camera in the basic threejs example on this page:

https://github.com/mrdoob/three.js/

var camera, scene, renderer;
var geometry, material, mesh;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.z = 1000;

    scene = new THREE.Scene();

    geometry = new THREE.CubeGeometry( 200, 200, 200 );
    material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.CanvasRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );

    document.body.appendChild( renderer.domElement );

}

function animate() {

    // note: three.js includes requestAnimationFrame shim
    requestAnimationFrame( animate );

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;

    renderer.render( scene, camera );

}

I've tried the following code:

var params = {
    z: 100
}

var gui = new dat.GUI();

gui.add(params, 'z', -500,500).step(5).onChange(function(value){
        changeCameraZ(value);
    });
function changeCameraZ(value){
    camera.position.z = value;
}

which works, but it means that I have to write a new function: changeBlah();

for each three.js variable I wish to change from the GUI. Is there a better, cleaner way of achieving this?

like image 836
Binaromong Avatar asked Sep 27 '12 10:09

Binaromong


People also ask

What is gui in threejs?

GUI is another very useful tool that we can use to learn about Three. js as it allows us to quickly add a very basic user interface which allows us to interact with our 3d scene and the objects within it.

Does Three js use WebGL?

js. Three. js is a cross-browser JavaScript library and application programming interface (API) used to create and display animated 3D computer graphics in a web browser using WebGL.

What three js can do?

Three. js allow you to use your GPU(Graphics Processing Unit) to render the Graphics and 3D objects on a canvas in the web browser. since we are using JavaScript so we can also interact with other HTML elements.


2 Answers

This one-liner should work.

gui.add( params, 'z', -500, 500 ).step(5).onChange( function( value ){ camera.position.z = value; } );
like image 32
WestLangley Avatar answered Oct 01 '22 15:10

WestLangley


You could also make use of how DAT.gui makes use of references.

gui.add( camera.position , 'z', -500, 500 ).step(5)

and an example

http://jsfiddle.net/2WKqL/2/

like image 145
Gero3 Avatar answered Oct 01 '22 15:10

Gero3