Question

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)
Was it helpful?

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).

OTHER TIPS

Find the angle between that vector and (1,0) (Right horizontal positive direction).

The math is:

A = (5,1) B = (1,0)

A.B = |A||B|cos(angle) -> angle = arccos((|A||B|)/(A.B))

Dot product, check geometric definition

Edit:

Another option is to use the cross product formula:

|AxB| = |A||B|sin(angle) -> angle = arcsin((|A||B|)/(|AxB|))

It will give you the angle you need.

There is an easier way to get full 360 degrees. What you're looking for, is Math.atan2:

deg = Math.atan2(obj.velocity.y,obj.velocity.x)*180/Math.PI;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top