..
#gamedev

Util Math for Games

Numbers and Vector 1D

pipe means absolute value

Distance

Use subtraction of numbers to get the distance.

distance(a,b) = |b - a|

Absolute

Use the absolute value to remove sign.

abs(a) = |a|

Sign

Use the absolute value to figure out the direction of vector.

sign(a)        = a / |a|
 10 / abs(10)  =  1.0
-10 / abs(-10) = -1.0
  0 abs(0)     = 0

Vector 2D

When we subtract vectors, like a - b, it's the same to ADD a flipped vector a + (-b). Let's see:

 b = (-4, 1)
-b = (4, -1)

a = (3,2)
d = a - b = (7,1)

1734379992.png

Vectors has only one value that represents the end of it. I mean, it doesn't have START and END.

Vector Length (magnitude)

If we have only Vector 1D, just compute the length of vector by subtract them. b - a.

But, in the Vector 2D, we need the Pythagorean Theorem.

Cˆ2 = aˆ2 + bˆ2

1734382257.jpeg

So, the formula is:

length(c) = Math.sqrt(c.xˆ2 + c.yˆ2)

a = (3,1)
b = (-2,2)
c = (a.x - b.x, a.y - b.y) = (5,-1)

length(a - b) = Math.sqrt(5ˆ2 + (-1)ˆ2) = 5.0990195135927845

When we use two pipe we are talking about the magnitude/length of something. ||b - a||

Normalize / Direction

Use the magnitude value to get normalized value.

normalize(a) = a / ||a||
â = a / ||a||

Dot Product

The dot product is the Vector multiplication like a.b

a.b = a.x * b.x + a.y * b.y

Scalar Projection:

We can use Scalar Projection to figure out if the vector is behind a object (represented by normalized vector - â).

â.b -> Normalized vector(a) and normal vector(b) multiplication

1734385424.png