Search code examples
javascriptvector2dangle

Determine movement vector's direction from velocity


I'm kinda confused with this one.

I have an object and I know it's velocities on axis x and y. My problem is how to determine the angle at which it's moving.

function Object(){
    this.velocity = {x: 5, y: 1};
}

Basically I Know that a vector's direction is x_projectioncos(deg) + y_projectionsin(deg), but I don't know how to get those projections since I only have the velocity, as I said I'm really confused.

#EDIT:

in addition to the accepted answer, here's what I did to get a full 360 degree spectrum

var addDeg = 0;
if(obj.velocity.x<0)
    addDeg = obj.velocity.y>=0 ? 180 : 270;
else if(obj.velocity.y<=0) addDeg = 360;

deg = Math.abs(Math.abs(Math.atan(obj.velocity.y/obj.velocity.x)*180/Math.PI)-addDeg)

Solution

  • I don't know how to get those projections since I only have the velocity

    Actually, what you seem to be missing is that you already have the projections. That's what x and y are.

    x is speed * cos(angle)

    y is speed * sin(angle)

    So y/x = sin(angle)/cos(angle) which is tan(angle) so angle=arctan(y/x).

    That's the angle rotating anti-clockwise starting from the x axis (with x pointing right and y pointing up).