I've noticed that many of stock scripts use the following method for calculating the distance between an entity and a player:
PlayerDX = g_Entity[e]['x'] - g_PlayerPosX;
PlayerDY = g_Entity[e]['y'] - g_PlayerPosY;
PlayerDZ = g_Entity[e]['z'] - g_PlayerPosZ;
PlayerDist = math.sqrt(math.abs(PlayerDX*PlayerDX)+math.abs(PlayerDY*PlayerDY)+math.abs(PlayerDZ*PlayerDZ));
The ai_soldier script contains the following comment "-- Detect player distance (note: possible optimization here)":
The equation can be simplified and optimized (probably not a noticeable performance difference at all) by eliminating the math.abs( ) calls (since the square of any number is always positive). So it should look like this:
PlayerDX = g_Entity[e]['x'] - g_PlayerPosX;
PlayerDY = g_Entity[e]['y'] - g_PlayerPosY;
PlayerDZ = g_Entity[e]['z'] - g_PlayerPosZ;
PlayerDist = math.sqrt(PlayerDX^2 + PlayerDY^2 + PlayerDZ^2);
It can be further optimized if you are comparing a known distance. If you are, you can eliminate the math.sqrt( ) call and simply square the known distance.
For example this:
PlayerDX = g_Entity[e]['x'] - g_PlayerPosX;
PlayerDY = g_Entity[e]['y'] - g_PlayerPosY;
PlayerDZ = g_Entity[e]['z'] - g_PlayerPosZ;
PlayerDist = math.sqrt(PlayerDX^2 + PlayerDY^2 + PlayerDZ^2);
if PlayerDist < 100 then
--Do something
end
Could become this:
PlayerDX = g_Entity[e]['x'] - g_PlayerPosX;
PlayerDY = g_Entity[e]['y'] - g_PlayerPosY;
PlayerDZ = g_Entity[e]['z'] - g_PlayerPosZ;
PlayerDist = PlayerDX^2 + PlayerDY^2 + PlayerDZ^2
--10000 is the 100 squared
if PlayerDist < 10000 then
--Do something
end
Hopefully this helps a bit.
Sean