I may as well put this into it's own little post...
One of the things that I've been doing with scripts in Unity is finding ways to disable objects based on distance. Naturally LODGroups are meant for that, but I'm referring to things such as lights, particles, and other things that don't have a mesh renderer component.
As I mentioned in the previous post, while something like "Vector3.Distance(a, b)" is convenient, it is also quite intensive. So when dealing with potentially hundreds of objects every frame, it can add quite a lot to the CPU overhead.
The solution is to use a fast distance calculation:
public static float FastDist2D(Vector3 a, Vector3 b)
{
Vector2 heading;
heading.x = a.x - b.x;
heading.y = a.z - b.z;
return heading.x * heading.x + heading.y * heading.y;
}
Since the action in most games takes place horizontally, it makes sense to simply use the X and Z coordinates without involving any square roots.
And an all encompassing binary distance check would look like this:
public static bool FastDistCheck2D(Vector3 a, Vector3 b, float d)
{
float distSqr;
Vector2 heading;
heading.x = a.x - b.x;
heading.y = a.z - b.z;
distSqr = heading.x * heading.x + heading.y * heading.y;
if(distSqr < d * d)
return true;
else
return false;
}
Clean and simple!
Calculating in 3D is just as easy of course, simply make "heading" a vector 3, and add the "y" component.
Wednesday, December 5, 2018
Subscribe to:
Posts (Atom)