Scripts / The Distance Formula

Author
Message
Hockeykid
17
Years of Service
User Offline
Joined: 26th Sep 2007
Location:
Posted: 13th Jun 2014 18:09
I've noticed that many of stock scripts use the following method for calculating the distance between an entity and a player:



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:



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:



Could become this:




Hopefully this helps a bit.



Sean

Defy
17
Years of Service
User Offline
Joined: 20th Aug 2007
Location:
Posted: 14th Jun 2014 09:43
Good read, thanks
PM
The Tall Man
10
Years of Service
User Offline
Joined: 24th May 2014
Location: Earth
Posted: 14th Jun 2014 19:37 Edited at: 14th Jun 2014 19:41
In C++, whenever I need to square something, I always multiply the variable by itself instead of squaring, because I've found it runs faster that way. I'd say it's highly likely that LUA's the same way, as it's all the same under the hood.



Very surprised they put the abs() function in the stock scripts, as it serves no purpose there.



Also, if you know the player and object will always be on the same (or virtually the same) Y level, you could eliminate the Y portion of the calculation.
PM

Login to post a reply

Server time is: 2024-12-22 05:10:25
Your offset time is: 2024-12-22 05:10:25