Search code examples
javascriptgame-physics

Need help for javascript and trigonometry


http://jsfiddle.net/techsin/CxFRC/15/ all chrome only click and drag, up and back arrow.

pastebin.com/gXS1J7zw

The Problem: I can't make c=$('.con') go/translate sideways. I have managed to do front and backward. But I cant workout the formula for sideways.

This is my first attempt. Use arrows keys, forward and backward works are in different function. But leftRight don't.

Code in question: you don't need to worry about rest of the code main logic for right left lies here. I have tried finding the perpendicular angle but it behaves opposite and then opposite of opposite.

First code that works and need no attention:

function forwBack(x){ 
   az+= x*(Math.cos((Math.PI/180)*ry))*Math.cos((Math.PI/180)*rx)*speed;
   ax-= x*(Math.sin((Math.PI/180)*ry))*Math.cos((Math.PI/180)*rx)*speed;
   ay+= x*(Math.sin((Math.PI/180)*rx))*speed; 
}

Now code that doesn't do what I want... translate perpendicular to vector.

     function rightLeft(x){
       az+= Math.sin(ry*(Math.PI/180))*(Math.cos((rx+90)*(Math.PI/180))*speed*x);
       ax-= Math.cos(ry*(Math.PI/180))*(Math.cos((rx+90)*(Math.PI/180))*speed*x);
       ay+= Math.sin((rx+90)*(Math.PI/180))*speed*x; 
    }

x is sign which determines left/right or forward/backward. Speed is hypotenuse here. Pi/180 for deg to radians. And 180/Pi for radians to deg. (rotation around x axis) rx and ry are defined in function ch..and represent rotation of main(.ma) container. rx is defined by vertical movement of mouse.

I don't need to do this, but I want to. I want to make 3d explorer like a hall.. Just for fun. I used to do this kind of stuff in flash like 9 years ago. I was a kid then.

MAIN problem is that sideways is not always -x or +x, it depends on how much outer container has been rotated(around xyz). So if m is rotated 90 around y axis only telling c to move x+ would make c actually look like it's going back or reducing in z.

After trying two days straight I can't fix this.

http://jsfiddle.net/techsin/hGkMj/1/ -- Checking out 3d

http://jsfiddle.net/techsin/hGkMj/6/ -- Checking out 3d

http://jsfiddle.net/techsin/9YjSC/3 I made this to get clear idea of what I was trying to do. Move mouse, & Use arrow keys. Need to click in the preview window.


Solution

  • I found the problem. In your function rightLeft, you are inverting x and y. I rewrote the function and it is working fine:

        function rightLeft(x){
            var dAy = 0 ; 
            var dAz = Math.cos((ry+90)*(Math.PI/180))*speed*x;
            var dAx = Math.sin((rx+90)*(Math.PI/180))*speed*x;
            console.log("dAx = " + dAx + " dAz = " + dAz + " dAy = " + dAy);
            ax-= dAx;
            az+= dAz;
            ay+= dAy;
        }
    

    Hope this helps!