Get spacing between units

At the moment, I’m trying out a few ideas. I made a system that can successfully control 512 troops without any lag, the only problem now is collisions.

This got me to the conclusion, that I wanted them spaced out, like they do it in Mount & Blade: Bannerlord

image

When a unit finds a target, they go towards it and damage it. Simple. Problem is, when they start stacking up on top of each other, the frames drop faster than my will to live on a Monday.

Here is the code running the units, don’t worry about the framework bit, I use that to run the code instead of a while loop. I would like to note that this is just a temporary code that I made to test my idea. If I can get it to work, I will rework it to the best of my abilities.

Framework.NPC:AddNPC(nil,NPC,function()
			if NPC and NPC.Parent and NPC:FindFirstChild("HumanoidRootPart") then
				local ClosestEnemy = nil
				
				for i,Enemy in pairs(CheckFolder:GetChildren()) do
					local Distance = (HRP.Position - Enemy.HumanoidRootPart.Position).magnitude
					
					if Enemy.Humanoid.Health > 0 and (not ClosestEnemy or Distance < ClosestEnemy[2]) then
						ClosestEnemy = {Enemy,Distance}
					end
				end
				
				if ClosestEnemy and ClosestEnemy[2] < 8 then
					ClosestEnemy[1].Humanoid:TakeDamage(15)
				else
					local TooClose = nil
					
					
					
					if TooClose then
					elseif ClosestEnemy then
						NPC.Humanoid:MoveTo(ClosestEnemy[1].HumanoidRootPart.Position - (CFrame.new(NPC.HumanoidRootPart.Position,ClosestEnemy[1].HumanoidRootPart.Position).LookVector * 6))
					end
				end
			end

The solution code doesn’t have to be efficient for 256 troops (Which both sides have), but rather 6, as that’s how many a player would be able to control at once.

Was messing around in studio for a bit, and I think I figured out how to do this. Here’s an example of my code:

local MaxRows = 5
local PerRow = 10
local SpaceBehind = 0
local Collisions = game:GetService("PhysicsService")
local CollisionGroup = Collisions:CreateCollisionGroup("NPCs")

local npcs = {}

for i = 1,MaxRows do
	local Space = 0
	for i = 1, PerRow do
		local npc = script.Dummy:Clone()
		npc:SetPrimaryPartCFrame(CFrame.new(0,5,0) * CFrame.new(Space,0,SpaceBehind))
		npc.Parent = workspace
		for i,v in pairs(npc:GetChildren()) do
			if v:IsA("BasePart") then
				Collisions:SetPartCollisionGroup(v, "NPCs")
			end
		end
		npcs[npc] = {XOffset = Space, ZOffset = SpaceBehind}
		Space += 7
	end
	SpaceBehind += 7
end

while task.wait() do
	for i,v in pairs(npcs) do
		local PointCF = workspace.Point.CFrame * CFrame.new(v.XOffset, 0, v.ZOffset)
		i.Humanoid:MoveTo(
			PointCF.Position
		)
	end
end

Here’s the results of my code:

1 Like

Looks awesome, but I was looking to keep distance between them as they are chasing a singular target. I’m totally gonna use the code for another part of the game though, thanks :slight_smile:

2 Likes