RTS game attack system "sorting" issue

I have this bizarre error in my RTS game attack system script.
It’s related to the sorting, more specifically the prioritization or selection of targets.
Here’s the issue and the way the script works.

  1. First, it loops through all units in the folder “InitializedUnits” and adds them to a table. Now, for every unit in that table, it loops again but this time looks for a “target” (for _, Target in pairs(UnitTable)) which is in the same table as the units. This target is selected by checking the difference between the two unit’s team attributes and doing a magnitude check. The prioritization should be random
    The error is, that it is not random at all. There is a clear bias for one side and weirdly, no matter how many times I try it again, the same side wins every time (i.e., Team B wins every time). This isn’t an issue with the units since they’re all duplicated on the same part, and if I recreate the units, the issue still happens. The side appears as if it’s picked randomly upon game start. It’s peculiar, to say the least.
    I fixed this before by storing the attack script in all the units, and instead of doing two loops, I only did one that checked the magnitude difference between the return of the TargetLoop (again, defined as a unit with a different team) and script.Parent. The issue is, that it is very unoptimized and makes the game unplayable past around 500 units, which I am not fond of. So, again, I tried to do it all in one script in ServerScriptStorage, but I got this issue.
    ATTACHED BELOW: GIF of the script and the script itself
    https://gyazo.com/83879c9f97fb3b7146ecc96e68d9c939

It is not random at all, it is based on the order in which they are added. You can test out that behavior here:

--!strict

local folder: Folder = Instance.new("Folder")

for i: number = 1, 10 do
	local part: Part = Instance.new("Part")
	part.Name = tostring(i)
	part.Parent = folder
end

for _: number, child: Instance in folder:GetChildren() do
	print(child.Name)
end

-- 1, 2, 3, etc.

In your case, you’d probably want to sort by distance using something like this:

for _, Unit in UnitsTable do
	-- sort for every unit iteration
	table.sort(UnitsTable, function(unitA, unitB)
		return
			unitA:GetAttribute("Team") ~= Unit:GetAttribute("Team") and
			(unitA.PrimaryPart.Position - Unit.PrimaryPart.Position).Magnitude < (unitB.PrimaryPart.Position - Unit.PrimaryPart.Position).Magnitude
	end)
	
	for _, Target in UnitsTable do
		-- your logic
		
		if Target:GetAttribute("Team") ~= Unit:GetAttribute("Team") then
			
		end
	end
end

In the future, post code using codeblocks instead of images next time:
```lua
– code here
```

1 Like

Would the bottom suggestion fix my issue? (I’m at school rn can’t test it out lol)

You’re going to have to modify and test it out for yourself.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.