02-23-2012, 03:33 PM
na_th_an Wrote:There's a much faster distance formula, which doesn't require square roots, albeit it's not as precise, but it works. It's what I use in my games - I can't afford a square root per frame so I just...
Roughly translated from C code, but should work:
Code:unsigned char distance (unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2) {
unsigned char dx = abs (x2 - x1);
unsigned char dy = abs (y2 - y1);
unsigned char mn = dx < dy ? dx : dy;
return (dx + dy - (mn >> 1) - (mn >> 2) + (mn >> 4));
}
So in a right angle triangle with sides A and B, and hypotenuse H, it returns (A+B) - (half the smallest of A and B) - (1/4 the smallest of A and B) + (1/16 the smallest of A and B) ?
I just put that into excel. That's...actually surprisingly good - though the error does go up as high as 7% sometimes. If you int the values, It's likely to be solid for x|y < 4, but can actually compound errors to 13%.