Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript / threejs - equation to move an object in a circle around a central y axis (in 3D space)

I am experimenting with threeJS, and I've got a camera positioned and looking at the origin point of a scene (0,0,0). I want to move that camera around in a circle around the y axis at a set distance (radius), while maintaining its focus on the origin, but I'm not sure how to set up the equation. Currently, I'm just rotating the object itself, but I'd like to be rotating the camera instead. Here's my code to move the mesh:

function checkRotation(){
    if (keyboard.pressed("left")){
        mesh.rotation.y += .05;
    }

    if (keyboard.pressed("right")){
        mesh.rotation.y -= .05;
    }
}

and here would be some sort of example of moving the camera:

camera.position.x = ??? (some equation to move its x position) camera.position.z = ??? (some equation to move its z position) camera.lookAt(mesh.position);

Any help you can provide would be great. Thanks!

like image 364
mheavers Avatar asked Apr 26 '12 21:04

mheavers


2 Answers

Bit of a late answer, but others may wish to take a look at the OrbitControls that comes with Three.js (in examples/js/controls). You can set it to autoRotate. It will take care of the maths for you.

var controls = new THREE.OrbitControls(camera);
controls.autoRotate = true;
controls.autoRotateSpeed = [whatever speed you want]

camera.lookAt(new THREE.Vector3(0,0,0));

Then in your requestAnimationFrame-called update function...

controls.update();

If you don't want the user to be able to control the camera position themselves, I'm sure you can find a way to disable it, or just extract the code that you need...

like image 30
poshaughnessy Avatar answered Sep 18 '22 12:09

poshaughnessy


You can set the position of the camera manually along the following lines:

// let theta be the amount you want to rotate by
var x = camera.position.x;
var z = camera.position.z;

camera.position.x = x * Math.cos(theta) + z * Math.sin(theta);
camera.position.z = z * Math.cos(theta) - x * Math.sin(theta);
camera.lookAt(mesh.position); // or camera.lookAt(0, 0, 0);

See http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions for the matrix equivalent for rotation about the x, y, and z axes.

You might also be able to adapt TrackballControls to use the keyboard and not the mouse.

Default Trackball behaviour: http://mrdoob.github.com/three.js/examples/misc_camera_trackball.html

Note: I haven't tested this yet - I'm at work.

like image 107
Iskar Jarak Avatar answered Sep 19 '22 12:09

Iskar Jarak