Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Optimizing function to get nearest object? (100+ moving objects) [Solved]

Asked by 8 years ago
Edited 8 years ago

I am currently working on a little RTS game project, and I have finished most of the basic unit movement, interactions etc. framework, and I am now moving onto optimization and visuals. The game is Filtering Enabled, and all movement and interaction calculations are done by individual clients. I am currently finding the most CPU usage coming from my method of finding objects in proximity to the individual units. I currently have it where all the units and their basic values such as ID, owner, current waypoint etc, are all stored within a table within each client. However, I am currently using FindPartsInRegion3witIgnoreList and the good old fashion .magnitude to find the distance between the units. Currently, I have it where every 1 second it updates all the units and their interactions, but the tables containing nearby and the nearest enemy/ally is updated every 2 seconds, and I am using (tick() - lastupdate) to achieve the multiple timings within one loop. Whenever I deactivate the finding of nearby and nearest units the script runs very well with minimal CPU usage, however when this function is in use at this interval, it can get up to 6% CPU usage when two players have 50 units, and they are all in very close proximity. So finally to my question, is there any other ways to optimize this system? I was wondering if there are any other methods to find the nearest objects or iterate through a table of existent objects. Any advice would be great. Below is my current code:

01local function findNearestID(unit,point,range)
02    local closestally = nil
03    local closestenemy = nil
04    local closestenemydist
05    local closestallydist
06    local ally,enemy = {},{}
07    local unitpos
08    local objs = Objects:GetChildren()--AllUnits
09    if unit == nil then
10        unitpos = point
11    else
12        unitpos = unit.Position
13        objs = ObjsRegion3PS(unitpos,unit.Range.Value*Vector3.new(1,1,1))
14        --ObjsRegion3PS finds all parts in Region3 centered at point and range
15        range = unit.Range.Value
View all 43 lines...
0
I just realized I was changing values in the interactions function which was really CPU intensive, this is actually pretty efficient already. Zhoutai189 0 — 8y

Answer this question