distance

From ZDoom Wiki
Jump to: navigation, search

Here is an ACS representation of a function similar to VectorLength.

function int fdistance (int tid1, int tid2)
{
	int len;
	int y = getactory(tid1) - getactory(tid2);
	int x = getactorx(tid1) - getactorx(tid2);
	int z = getactorz(tid1) - getactorz(tid2);

	int ang = vectorangle(x,y);
	if(((ang+0.125)%0.5) > 0.25) len = fixeddiv(y, sin(ang));
	else len = fixeddiv(x, cos(ang));

	ang = vectorangle(len, z);
	if(((ang+0.125)%0.5) > 0.25) len = fixeddiv(z, sin(ang));
	else len = fixeddiv(len, cos(ang));

	return len;
}

The above function works by rotating the points so they align with an axis. It runs in a constant time and is almost always faster than the more recognizable pythagorean version below:

function int distance (int tid1, int tid2)
{
	int x, y, z, d;
	x = GetActorX(tid1) - GetActorX(tid2) >> 16; // Convert fixed point to integer
	y = GetActorY(tid1) - GetActorY(tid2) >> 16;
	z = GetActorZ(tid1) - GetActorZ(tid2) >> 16;
	d = sqrt( x*x + y*y + z*z );
	return d;
}