I have a label which is linked to an anchor. The problem is to find on which one of the four side of the label (which is a Rectangle) should be linked to the anchor.
|label|<----[anchor]
So I created a vector from the label center to the top right of the label (v1), a vector from the center to the bottom right (v2), to the top left (v3) and bottom left (v4). I also create a vector from the center of the label to my anchor (v).
My problem is to find if v is between (v1,v2) , (v1,v3) , (v1, v4) or(v4, v2) so I can know from which side I should link my anchor.
to calculate if a vector v is between v1 and v2 I use the following formula :
(crossProduct v1, v >= 0 and crossProduct v, v2 >= 0) or
(crossProduct v1, v <= 0 and crossProduct v, v2 <= 0)
where crossProduct is calculated with the following formula:
v1.y * v2.y - v1.x * v2.x
However I'm not able to find the correct side of the rectangle.
I thought of a method that uses dot product (Edit: For code involving cross product, see the end of the answer). Refer this diagram:
Find the cosine of the angle between $\vec {v\,}$ and $\vec {v_1}$ using dot product, as: $$ \cos \theta = \dfrac{\vec {v\,}\cdot\vec {v_1}}{|\vec{v\,}||\vec{v_1}|}$$ Then find the cosine of the angle between $\vec {v_2}$ and $\vec {v_1}$ and compare the two cosines. The angle with larger cosine will be the smaller angle. (If the cosine comes negative for the pair including $\vec {v\,}$, then it surely can't be near that vector with which it was paired). Repeat this for other 3 vectors.
Note that you wouldn't need to find the angle between any two vectors.
Important Edit: Change the code block:
to
or simply
To essentially check if the cross product in both cases is of same or opposite sign. Hope this helps!