Hello! I’m trying to make a monster that follows the player. I managed to make the monster move to a part, but I’m not sure how to make it chase the player.
The Script:
local PathFindingService = game:GetService("PathfindingService")
local human = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("HumanoidRootPart")
local path = PathFindingService:CreatePath()
path:ComputeAsync(torso.Position, game.Workspace.endingPart.Position)
local waypoints = path:GetWaypoints()
for i, waypoint in pairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
human:ChangeState(Enum.HumanoidStateType.Jumping)
end
human:MoveTo(waypoint.Position)
human.MoveToFinished:Wait(2)
end
while true do
human:MoveTo(game.Workspace.endingPart.Position)
wait(0.3)
end
You’ll need to continuously re-call your code to make the monster keep chasing the player & update the destination.
You are re-calling MoveTo so it can reach the destination, but you also need to continually re-calculate the end position and the path to get there as well.
Oh, I see. So, what you can do is get a table of players from the players service. Then, loop through that table and find which player is the closest based on the monster’s position relative to each player’s character’s position.
Players = game:GetService("Players")
local closest_player_distance = math.huge
local closest_player_hrp = nil
for i, player in pairs(Players:GetPlayers()) do
-- Check if the player has a character
local character = player.Character
if character then
local hrp = character:FindFirstChild(“HumanoidRootPart”)
if hrp then
local this_distance = (torso.Position - hrp.Position).Magnitude
if this_distance < closest_player_distance then
closest_player_distance = this_distance
closest_player_hrp = hrp
end
end
end
end
-- closest_player_hrp now has the closest player’s hrp
I recommend you put this code in a function so you can constantly re-run it to get the most up to date closest player. If you don’t, it will keep returning the same result.
How do I implement this in to the script? I’m sorry, my knowledge of Lua is very limited
Edit: I’m just trying to get the monster to pathfind to the player.