I am trying to move on enemy to the other enemy with Pathfinding but I can’t seem to get it to work but there is also no error in the code.
The code:
local RS = game:GetService("ReplicatedStorage")
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
-- Configuration
local spawnFolder = game.Workspace.Spawns
local team1Spawn = spawnFolder.Team1.SpawnTeam1
local team2Spawn = spawnFolder.Team2.SpawnTeam2
local team1 = game.Teams.Team1
local team2 = game.Teams.Team2
local enemyFolder = RS.EnemiesModels
local numEnemies = 1 -- Set the number of enemies to spawn for each team
local targetUpdateInterval = 1 -- Set the interval (in seconds) for updating the target position
local enemyTargets = {}
local function moveAlongPath(enemyDummy, path)
while path.Status == Enum.PathStatus.Success do
local waypoints = path:GetWaypoints()
for i, waypoint in ipairs(waypoints) do
enemyDummy.Humanoid:MoveTo(waypoint.Position)
enemyDummy.Humanoid.MoveToFinished:Wait()
end
end
end
local function updateTargetPosition(enemyDummy)
local targets = Players:GetPlayers()
local closestTarget = nil
local closestDistance = math.huge
for _, player in ipairs(targets) do
if player.Team ~= enemyDummy.Team then
local distance = (player.Character.HumanoidRootPart.Position - enemyDummy.HumanoidRootPart.Position).Magnitude
if distance < closestDistance then
closestTarget = player.Character.HumanoidRootPart.Position
closestDistance = distance
end
end
end
enemyTargets[enemyDummy] = closestTarget
end
local function spawnEnemies(team, spawnPoint)
for i = 1, numEnemies do
local enemy = enemyFolder:FindFirstChild("Enemy" .. team.Name)
if enemy then
enemy = enemy:Clone()
enemy.Parent = game.Workspace.Enemies[team.Name.. "Enemies"]
enemy:SetPrimaryPartCFrame(spawnPoint.CFrame)
enemy.Values.Team.Value = tostring(team)
spawn(function()
while true do
task.wait(targetUpdateInterval)
updateTargetPosition(enemy)
end
end)
spawn(function()
while true do
task.wait(0.1)
local targetPosition = enemyTargets[enemy]
if targetPosition then
local path = PathfindingService:CreatePath()
path:ComputeAsync(enemy.HumanoidRootPart.Position, targetPosition)
moveAlongPath(enemy, path)
end
end
end)
end
end
end
spawnEnemies(team1, team1Spawn)
spawnEnemies(team2, team2Spawn)
What I try to do:
https://streamable.com/fhwlwt
Thats all, maybe you can help me. (I am not good with Pathfinding so if the code doesnt make sense thats why)