Math in Unity : Intersections (Part I)

Today we talk about intersections.

Probably from now on things will get slightly complicated, but as always, when we know what to do and how to do it, the real difficulty lies in understanding the formulas and translating them into the code.

First of all, what is an intersection?
In a nutshell, it is the point where two lines, precisely, intersect.

And how do we calculate the intersection point?

Let’s examine the image above.
We have two lines, with two points of origin A and B and their respective vectors v and u.

The intersection point formula is

A + vt = B + us

To simplify it, we remove points A and B and replace them with a Vector.

vt = B - A + us

Let’s go further: we know that B - A generates another Vector, C, which will be the distance between B and A.

So we can replace part of the formula with c.

vt = c + us

Now, since we don’t know neither s nor t, we have to approach the problem from another point of view : the 2D PERP VECTOR.

Let’s briefly explain what 2D Perpendicular Vector is.

If we have this Vector

The 2D perp vector is a vector that is 90 degrees perpendicular to another.

And it can be calculated like this

The small inverted T means “perpendicular”.
The perpendicular of Vector v is equal to (-y, x).
Nothing crazy right?
This means that if we have a Vector (3, 8),
the perpendicular is
v perp = (-8, 3)
In this case, as the x becomes negative, the perpendicular will be 90° but counterclockwise.

Another useful thing to know is that if the Dot product of
v perp and v is = 0,
then the angle will be 90°.

To confirm this, let’s test with two previous Vectors
The dot product of (3, 8) and (-8, 3) is

(3 * -8) + (8 * 3) = -24 + 24 = 0

This same formula can be expressed like this:

Let’s take an example to better understand:
given two Vectors, if the perpendicular of v is (3, 8) and the Vector u is (2, 4)

v perp = (3, 8)
u = (2, 4)

Using the formula above

v perp Dot u = (3 * 2) + (8 * 4) = 6 + 32 = 38

Now, applying the inverse formula, if the perpendicular of v is (3, 8), this means that the values of v will be (8, -3)
And for u (2, 4), the perpendicular will be (-4, 2)

u perp = (-4, 2)
v = (8, -3)

But we need the nagative u perp, so
-u perp = (4, -2)

And if we apply the formula

-u perp Dot v = (8 * 4) + (-2 * -3) = 32 + 6 = 38

As we can see, we have the same result.

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!