when my fighting NPCs end up in a 1v2 situation, the NPCs that are teaming up end up clumping up and hitting each other. is there a way that I can make them spread out and surround the enemy realistically?
4 Likes
I’d look into boids and general flocking algorithms. Basically the general idea is for each fighting NPC, loop through all of the other fighting NPCs and get the distance between itself and the other fighting NPC, and if that distance is smaller than the distance you want between them then get the direction to move away from other NPC(or you could just weight it, could be nice so it moves towards npcs its not close enough to). Add all of the avoidance move directions up and divide by number of other fighting NPCs/just get the average move direction.
Here’s some code to quickly show the general idea of how the math works:
for _, npc in workspace.NPCs do
local moveDirection = Vector3.zero
local numNpcsApplied = 0
for _, otherNpc in workspace.NPCs do
if npc == otherNpc then
continue;
end
local diff = otherNpc.HumanoidRootPart - npc.HumanoidRootPart --The direction of the npc to the othernpc
local dist = diff.Magnitude
if dist < GROUPING_DISTANCE then
numNpcsApplied += 1
moveDirection += -diff.Unit --by reversing the direction we're instead getting the direction to move away from othernpc
end
end
if numNpcsApplied ~= 0 then
moveDirection /= numNpcsApplied --Subtract 1, so you can include the own npc. Here we are getting average avoidance direction.
end
--Apply move direction to ai
end
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.