Keep updating player position

I’m making a escape game where this monster chases you through a maze and I’ve made a script where it detects players and chases them but the monster only follows the players previous position, this makes the monster extremely easy to dodge. I want it to continuously follow the player.

this is the code

``

if distance > 3 then
	for index, waypoint in pairs(path:GetWaypoints()) do
		local newTarget = findTarget()
		if newTarget == target then
			--checking waypoints
			local part = Instance.new("Part", workspace)
			part.CanCollide = false
			part.Anchored = true
			part.Position = waypoint.Position
			humanoid:MoveTo(waypoint.Position)
			humanoid.MoveToFinished:Wait()
		elseif newTarget ~= target then
			--there are closer targets! switch!
			path = getPath(newTarget.HumanoidRootPart)
		else
			break
		end
	end
else

	--monster.Head.JumpScare:Play()

	--local playerDeath = game.ReplicatedStorage.Events:WaitForChild("playerDeath")
	--local player = game.Players:GetPlayerFromCharacter(target)
	--playerDeath:FireClient(player, monster)

	--local attackAnim = humanoid:LoadAnimation(script.Attack)
	--attackAnim:Play()
	--attackAnim.Stopped:Wait()
	--target.Humanoid.Health = 0
end

``

yeah this was supposed to be in a function but roblox refuses to make that part of the code

1 Like

try this

local monster = script.Parent -- Assuming the script is a child of the monster
local pathfindingService = game:GetService("PathfindingService")

local function findClosestPlayer()
    local players = game.Players:GetPlayers()
    local closestPlayer = nil
    local shortestDistance = math.huge

    for _, player in pairs(players) do
        local character = player.Character
        if character then
            local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
            if humanoidRootPart then
                local distance = (humanoidRootPart.Position - monster.Position).Magnitude
                if distance < shortestDistance then
                    closestPlayer = humanoidRootPart
                    shortestDistance = distance
                end
            end
        end
    end

    return closestPlayer
end

while true do
    local target = findClosestPlayer()
    if target then
        local path = pathfindingService:CreatePath({
            AgentRadius = 2,
            AgentHeight = 5,
            AgentCanJump = true,
            AgentJumpHeight = 10,
            AgentMaxSlope = 45,
            })
        path:ComputeAsync(monster.Position, target.Position)
        path:MoveTo(monster)
    end

    wait(1) -- Adjust the update frequency as needed
end