Ok, so my goal is to create a NPC that seamlessly moves to the destination
without running into walls or getting stuck, I have written a script that works pretty decent in another game, but this one is just not working in this other game, I do not know if I messed with it too much, but my only real goal is for the movement to be smart enough there is no colliding/walking against walls and makes a smart path to reach the target.
Current Code
local rs = game:GetService("ReplicatedStorage")
local MoveHumanoidEvent = rs.MoveHumanoid
MoveHumanoidEvent.OnServerEvent:Connect(function(player, npc, destination)
local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local jumpHeight = 7.2
if not npc.PrimaryPart then
error("NPC model does not have a PrimaryPart set.")
end
local function createPath(target)
local path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
AgentJumpHeight = jumpHeight,
AgentMaxSlope = 45,
})
local success, errorMessage = pcall(function()
path:ComputeAsync(npc.PrimaryPart.Position, target.Position)
end)
if not success then
warn("Path computation failed: " .. errorMessage)
return nil
end
return path
end
local function findObstacle()
local ray = Ray.new(npc.PrimaryPart.Position, npc.PrimaryPart.CFrame.LookVector * 10)
local hitPart, hitPosition = workspace:FindPartOnRay(ray, npc)
return hitPart
end
local function canMoveTo(position)
local ray = Ray.new(npc.PrimaryPart.Position, (position - npc.PrimaryPart.Position).unit * 10)
local hitPart, hitPosition = workspace:FindPartOnRay(ray, npc)
return not hitPart
end
local function walkAroundObstacle(obstacle)
local start = npc.PrimaryPart.Position
local direction = (destination.Position - start).unit
local sideStep = direction:Cross(Vector3.new(0, 1, 0)).unit * 10
local leftStep = start + sideStep
local rightStep = start - sideStep
if canMoveTo(leftStep) then
npc.Humanoid:MoveTo(leftStep)
elseif canMoveTo(rightStep) then
npc.Humanoid:MoveTo(rightStep)
else
warn("Cannot move around the obstacle")
end
end
local function moveToDestination()
local path = createPath(destination)
if path and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for _, waypoint in ipairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
npc.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
npc.Humanoid:MoveTo(waypoint.Position)
else
npc.Humanoid:MoveTo(waypoint.Position)
end
npc.Humanoid.MoveToFinished:Wait()
end
else
warn("Path not found or incomplete, trying to walk around the obstacle")
local obstacle = findObstacle()
if obstacle then
walkAroundObstacle(obstacle)
end
end
end
moveToDestination()
end)
If you can help me figure this out, that would be gratefully appreciated! I also want to let you know if you do a basic:
npc:MoveTo(destination)
It works, but it collides with a wall before meeting the target and I do not want that.