If you have to manipulate lines in any way, the Dot Product is the first thing to try using because it is very easy to calculate. Computers are relatively slow at calculating trigonometric functions. Calculating line length requires a square-root call which is also slow. This can sometimes be avoided if the calculations are ordered carefully.
The dot product is the sum of products of the vector elements, so for two 2D vectors v1=(dx1,dy1) and v2=(dx2,dy2) the Dot Product is:
If the two vectors are both Unit Vectors (length=1) then the Dot Product will vary from -1 to +1 inclusive (written [-1,1]).
If you're more used to Trigonometry, the Dot Product is the lengths of the two vectors multiplied together and to the cosine of the angle between the vectors:
- If the Dot Product is +1, the unit vectors are both pointing in the same direction.
- If the Dot Product is zero, the unit vectors are perpendicular (at right-angles to each other).
- If the Dot Product is -1, the unit vectors are pointing in opposite directions.
A•B = |A||B|cos(θ)
So dividing the Dot Product by the length of one vector gives the projection onto the other vector as shown:
The line colours here are equivalent to those in the interactive diagram.
(A•B) = |A|cos(θ)
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.