-
What do you want to achieve? I want it so the “Enemy” Npc only attacks the player if it can see it.
-
What is the issue? at the moment it only chases the player if its within a certain Stud radius.
-
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!