Im trying to make a NPC system that uses pathfinding to get a destination. My NPC is hostile and uses weapons (rocket launcher). If a player is nearby how would I make the NPC reroute from its current destination, to the player (trying to kill the player) then going back to its destination.
I couldn’t think of any ideas of how i would trigger or detect the event.
When I tried, the only alternative I found is making the weapon have its own AI script and just shoots the nearest player. (Which looks weird.)
Any questions or clarifications reply to this topic, and ill be happy to reply .
1 Like
Have the NPC go to its destination unless there is a nearby player.
Destination = Vector3.new(0,0,0) --Where its going to
NPC_Range = 50 --How far the NPC can detect a player
function findClosestPlayer()
local closestPlayer = nil
local closestDistance = math.huge
for _,player in pairs(game.Players:GetChilren()) do
if player.Character then
local distance = (player.Character.HumanoidRootPart.Position-NPC.HumanoidRootPart).magnitude
if distance <= NPC_Range and distance < closestDistance then --If the player is in range and its the closest one so far
closestDistance = distance
closestPlayer = player
end
end
end
return closestPlayer
end
while NPC.Parent ~= nil do--While it's alive
local closestPlayer = findClosestPlayer()
if closestPlayer ~= nil then
--Follow the player.. You can make it so that the NPC follows the player until the player is out of range or just for this one loop, so that it keeps finding the closest player.
else
--Go to its destination
end
wait(1) --Time until it tries to find another player to attack
end
2 Likes
Thank you so much!
Ill be sure to use this for future scripts.
1 Like