How to make a AI that can move to a moving part

Hello there, devs of roblox,

This is my first time posting in DevForum, so I need a few help here.

What I want to achieve?

  • How can I make a NPC that can move to a moving object like a moving Part or Player without going through the wall.
  • Move randomly if there are no player/target

Your help is greatly appreciated

If there are players, then you can make it either repeatedly pathfind or move to the closest player’s HumanoidRootPart (You can find the closest player using magnitude) If there are no players or parts, then generate a random vector3 value, make the humanoid pathfind and walk to it, then generate another vector3 value and repeat everything again.

Use PathfindingService! Here is an example:

local PathfindingService = game:GetService("PathfindingService")

local character = script.Parent -- Add the script inside the AI
local humanoid = character:WaitForChild("Humanoid")
local torso = character:FindFirstChild("HumanoidRootPart")

local path = PathfindingService:CreatePath()
path:ComputeAsync(torso.Position, workspace.Part.Position) -- Change "workspace.Part.Position" to your part
local waypoints = path:GetWaypoints()

for i, waypoint in pairs(waypoints) do
     if waypoint.Action == Enum.PathWaypointAction.Jump then
          humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
     end

     humanoid:MoveTo(waypoint.Position)
     humanoid.MoveToFinished:Wait()
end

If this doesn’t help, I don’t know what will lol

1 Like