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:
01 | local function findNearestID(unit,point,range) |
02 | local closestally = nil |
03 | local closestenemy = nil |
04 | local closestenemydist |
06 | local ally,enemy = { } , { } |
08 | local objs = Objects:GetChildren() |
12 | unitpos = unit.Position |
13 | objs = ObjsRegion 3 PS(unitpos,unit.Range.Value*Vector 3. new( 1 , 1 , 1 )) |
15 | range = unit.Range.Value |
19 | local obj = objs [ i ] -- [ 1 ] |
20 | if obj ~ = unit and obj:FindFirstChild( "ID" ) then |
21 | local mag = (obj.Position - unitpos).magnitude |
22 | local comparison = (closestallydist or 1000 ) |
23 | local comparison 2 = (closestenemydist or 1000 ) |
24 | local ID = obj.ID.Value |
25 | local splr = obj.Owner.Value |
26 | if splr ~ = plr and range > mag then |
27 | table.insert(enemy, { obj,ID,splr } ) |
28 | if mag < = comparison 2 then |
30 | closestenemydist = mag; |
32 | elseif range > mag then |
33 | table.insert(ally, { obj,ID,splr } ) |
34 | if mag < = comparison then |
36 | closestallydist = mag; |
42 | return ally,enemy,closestally,closestenemy |