Only start chasing if the NPC can see the player

  1. What do you want to achieve? I want it so the “Enemy” Npc only attacks the player if it can see it.

  2. What is the issue? at the moment it only chases the player if its within a certain Stud radius.

  3. What solutions have you tried so far? I am aware that you have to use a raycast of somesort however Im not sure how to.

local monster = script.Parent
local hum = monster.Humanoid

local ps =  game:GetService("PathfindingService")
monster.PrimaryPart:SetNetworkOwner(nil)
local attacked = false


local function findTarget()
	local players = game.Players:GetPlayers()
	local maxDistance = 30
	local nearestTarget
	
	for i, player in pairs(players) do
		if player.Character then
			local target = player.Character
			local distance = (monster.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
			
			if distance < maxDistance then
				nearestTarget = target
				maxDistance = distance
			end
		end
	end
	return nearestTarget
end

local function getpath(destination)
	
	local path = ps:CreatePath()
	path:ComputeAsync(monster.HumanoidRootPart.Position, destination.Position)
	
	return path
	
end

local function attack(target)
	local distance = (monster.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
	
	if distance > 2.5 then
		script.MentionOfKidnappers:Play()
		hum:MoveTo(target.HumanoidRootPart.Position)
	else
		if attacked == false then
			attacked = true
			target.Humanoid.Health = 0
			wait(0.2)
			attacked = false
		end
	end
end

local function walkTo(destination)
	
	local path = getpath(destination)
	
	for i, waypoint in pairs(path:GetWaypoints()) do
		local target = findTarget()
		
		if target then
			attack(target)
			break
			
		else
			hum:MoveTo(waypoint.Position)
			hum.MoveToFinished:Wait()
		end
	end
end

local function patrol()
	local waypoints = workspace.Waypoints:GetChildren()
	local randomNum = math.random(1, #waypoints)
	walkTo(waypoints[randomNum])
end

while wait() do
	patrol()
end

This is the script. Thanks!

This is the tutorial I used some time ago.

The monster only starts chasing you when it sees you and when you are in range. If you hide behind a wall after the monster had seen you, it walks to the last position it saw you at.

If you get out of radius or the monster can’t see you for a certain amount of time, it returns to its waypoints and patrols around there.

Edit:
I forgot to mention that you can use custom walk and attack animations for your monster in this tutorial.

1 Like

tysm ill try this! CharLimit30

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.