Dot Product:Red Length relative to green =
Blue Dot Green
(Length of Green) squared
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(θ)
Note that the value calculated in the interactive diagram is the relative length of the red line to the green line which avoids the need for a square-root in the length calculation.
Red Length relative to A =(Blue Dot Green) ÷ ((Length of Green) squared)
=(A•B) ÷ (A.dx*A.dx + A.dy*A.dy)
=(A.dx*B.dx + A.dy*B.dy)
(A.dx*A.dx + A.dy*A.dy)
This value will vary in the range [0,1] as long as the red line is within the green line.
If this value was multiplied by the length of the green line, that [0,1] range would become [0,length of green].
So dividing by the length squared avoided a square root and gave a unit interval that can be mapped (simply by multiplying) for other uses.
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.