In 2D vector graphics it is desirable to generally avoid trigonometric functions, as these are quite computation intensive. The above formulas build a good foundation to approach this goal.
In order to avoid angles we start to discuss them first. A 2D vector can be decomposed into it's magnitude and unit vector.
a = a · ua
The unit vector can be expressed by sin and cos of its angle to the positive x-axis.
ua = cos αsin α
This unit vector obviously has the required magnitude of "1", since
u2a = sin2 α + cos2 α = 1
Now consider another vector
b = b · cos βsin β
The dot product yields
a · b = a b (cos α · cos β + sin α · sin β)
Using the addition theorem of trigonometry this equation can be rewritten as
(7) a ·
b = a b cos (β − α) = a b cos φ
simultaneously introducing the angle φ = β − α from vector a to vector b.
In a similar manner we calculate the dot product
a^· b = a·b (sin β · cos α − cos β · sin α)
and apply again the addition theorem of trigonometry
(8) a^·
b = a b sin (β − α) = a b sin φ
Equations (7) and (8) can be taken as the basis for rather efficient expressions of the trigonometric functions of an angle φ between two vectors a and b.
(9) sin φ =
a· b^a · b =
ax by − ay bxa · b
(10) cos φ =
a · ba · b =
ax bx + ay bya · b
(11) tan φ =
a· b^a · b =
ax by − ay bxax bx + ay by
with
a · b = √(a2x + a2y) · √(b2x + b2y)
The above formulas are very convenient in case of two given vectors and the requirement to use trigonometric functions of the angle φ between them for continuative calculation.
If you really need the angle φ itself, I strongly recommend to use equation (11) , which is
- most efficient, since there is no square root to be calculated.
- supported by nearly all programming languages via their
atan2
function, which takes into consideration the angle's sign corresponding to the associated quadrant.