Friday, October 2, 2015

Basic Math for Game Developers- (How to find the nearest object to point) -- Part 01

Hello devs today I going to explain some very basic math for game developers. So lets get started at first we view a very basic game scenario .

Here is a player P and enemy e1 and e2  we have to determine the which enemy is closer to the player respect to the origin and y. So that we have to do some basic math and it’s the famous Pythagorean formula, a quick review - The sum of the areas of the two squares on the legs (a and b) equals the area of the square on the hypotenuse (c).  a^2+b^2 = c^2.

So what we have we the coordinates of e1(x,y) and e2(x,y), we draw triangle with these coordinates respect to the player like this.

We have to find out the hypotenuse (? marked) assume that the hypotenuse for e2 is H1 and for e2 is H2. Now according to the Pythagorean formula,

H1^2 =  x1^2 +  y1^2 ;
H1 = sqrt (x1^2 +  y1^2 );
And , H2 = sqrt (x2^2 +  y2^2 );

Lest have some simple calculation assume that x1=4, y1=5 and x2=3, y2=4.
So H1 =  sqrt(41) = 6 (absolute value)  and H2 = sqrt(25) = 5.

So now we know that H2<H1 that means e2(enemy2) is closer to the player.

But there is a performance issue if you noticed the calculation above, we have sqrt() twice the values.  The sqrt() is very expensive operation just think a game scenario we have players and enemies, they are moving and in our update() function calculating sqrt continuously and as a result our game will be slowing down.
But you can easily efficient the calculation ,

H1^2 =  x1^2 +  y1^2 ;
H2^2 =  x2^2 +  y2^2 ;
Forget about the sqrt we just do the following way,
x1^2 +  y1^2 = 41
x2^2 +  y2^2 = 25
at this moment 25<41,now we have our desired enemy and that’s it.

Thanks for reading.