Hello, this is my first ever post here! I’m trying to get my enemy NPCs to reach a goal point in my game, but they’re struggling to find a path if the goal is too far away.
-- references
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local humRootPart = npc:WaitForChild("HumanoidRootPart") -- HumanoidRootPart is required for moving the NPC
local map = game.Workspace.TestMap
local nodes = map.WayPoints:GetChildren() -- Pre-set waypoints in the map
-- services
local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
-- reference to the objective
local goal = map:WaitForChild("Objective")
-- function to move NPC to the goal
local function moveToGoal()
local path = PathfindingService:CreatePath({
AgentRadius = 3, -- Radius of the NPC (adjust based on NPC size)
AgentHeight = 6, -- Height of the NPC (adjust based on NPC height)
AgentCanJump = false, -- Set to true if the NPC can jump
AgentMaxSlope = 45 -- Maximum slope angle the NPC can walk up
})
-- calculates path from NPC starting point to the goal
path:ComputeAsync(humRootPart.Position, goal.Position)
-- checks if path is valid
if path.Status == Enum.PathStatus.Success then
-- gets waypoints
local waypoints = path:GetWaypoints()
-- moves npc to each waypoint
for _, waypoint in pairs(waypoints) do
-- For each waypoint, create a part to visualize the path
if RunService:IsStudio() then
local part = Instance.new("Part")
part.Shape = Enum.PartType.Ball
part.Material = Enum.Material.Neon
part.Size = Vector3.new(0.6, 0.6, 0.6)
part.Position = waypoint.Position
part.Anchored = true
part.CanCollide = false
part.Parent = game.Workspace
part.BrickColor = BrickColor.new("Bright blue")
game:GetService("Debris"):AddItem(part, 5) -- Deletes the part after 5 seconds
end
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait() -- Wait until NPC reaches the waypoint
-- If the waypoint is a jump point, make the NPC jump
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
if humanoid and goal.Touched == true then
print("Enemy has reached goal!")
end
end
else
warn("Path not found")
end
end
-- calls the function
moveToGoal()
I tried using the waypoints I’ve placed on the map to help the NPC navigate easier, but it seems to only head toward the nearest waypoint only, and not the goal.
I really appreciate any advice that can help me figure out on how I can go on about this. Thank you!