Search code examples
mathvectorformulaanglealgebra

calculate angle from vector to coord


I am breaking my head trying to find an appropriate formula to calculate a what sounds to be an easy task but in practice is a big mathematical headache.

I want to find out the offset it needs to turn my vector's angle (X, Y, Angle) to face a coord ( X, Y )

enter image description here

My vector won't always be facing 360 degrees, so i need that as a variable as well.. Hoping an answer before i'm breaking my pc screen. Thank you.


Solution

  • input

    • p1 = (x1,y1) point1 (vector origin)
    • p2 = (x2,y2) point2
    • a1 = 360 deg direction of vector
    • assuming your coodinate system is: X+ is right Y+ is up ang+ is CCW
    • your image suggest that you have X,Y mixed up (angle usually start from X axis not Y)
    • da=? change of a1 to match direction of p2-p1

    solution 1:

    • da=a1-a2=a1-atanxy(x2-x1,y1-y1)
    • atanxy(dx,dy) is also called atan2 on some libs just make sure the order of operands is the right one
    • you can also use mine atanxy in C++
    • it is 4 quadrant arctangens

    solution 2:

    • v1=(cos(a1),sin(a1))
    • v2=(x2-x1,y2-y1)
    • da=acos(dot(v1,v2)/(|v1|*|v2|))

    or the same slightly different

    • v1=(cos(a1),sin(a1))
    • v2=(x2-x1,y2-y1)
    • v2/=|v2| // makes v2 unit vector, v1 is already unit
    • da=acos(dot(v1,v2))

    so:

    da=acos((cos(a1)*(x2-x1)+sin(a1)*(y2-y1)/sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)));
    

    [notes]

    • just change it to match your coordinate system (which you did not specify)
    • use radians or degrees according to your sin,cos,atan dependencies ...