Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3d trigonometry equation

I'm trying to write a small 'perspective' javascript app that allows me to fly through a set of x,y,z points that inhabit a 3d space.

I have the concept of a camera which changes its rotation and xyz position, while each point maintains a constant xyz point.

I then have a set of equations that works out how the camera's x,y,z coordinates should be adjusted for flying directly forwards. The x,y,z adjustments obviously depend upon the rotation of the camera.

It almost works, but at certain 'attitudes' the camera position adjustment goes wrong and the flightpath doesn't go straight ahead but goes off at an angle, or even reverses. The equations for working out the projection are as follows:

var directionFactor = 1;
if (direction == 'backward') directionFactor = -1;

    sx = Math.sin(cameraView.rotX);
    cx = Math.cos(cameraView.rotX);
    sy = Math.sin(cameraView.rotY);
    cy = Math.cos(cameraView.rotY);
    sz = Math.sin(cameraView.rotZ);
    cz = Math.cos(cameraView.rotZ);


    // Z-Axis
    ztrig = Math.sqrt((cx * cx) + (cy * cy)) * (cx * cy);
    cameraView.z = cameraView.z + directionFactor * 
                                           (Math.abs(airspeed / 15) * ztrig);

    // Y-Axis
    ytrig = Math.sqrt((sx * sx) + (cz * cz)) * (sx * cz);
    cameraView.y = cameraView.y + directionFactor *
                                            (Math.abs(airspeed / 15) *ytrig);

    // X-Axis
    xtrig = Math.sqrt((cz * cz) + (sy * sy)) * (cz * sy);
    cameraView.x = cameraView.x - directionFactor * 
                                             (Math.abs(airspeed / 15) * xtrig);

Obviously my equations aren't quite right. Can anyone tell me where I'm going wrong? Much appreciated and thanks.

like image 394
Journeyman Avatar asked Mar 27 '11 10:03

Journeyman


1 Answers

You have some errors in your equations. (They are valid in the 2d case but not in 3d)

when you calculate

sx = Math.sin(cameraView.rotX);

It does make sense in 2d since :

sx = Math.sin(cameraView.rotX) = x/SQRT(y*y + x*x) 

where (x, y) is the position of the camera. But in 3d it's more complicated : enter image description here

In 3d :

enter image description here

enter image description here

enter image description here

Thus to obtain the cartesian coordinate :

enter image description here

enter image description here

enter image description here

You may also use 3d matrix to perform rotation.

like image 136
3 revs Avatar answered Nov 20 '22 00:11

3 revs