How to make NPCs change destinations. (Read Desc)

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 :smile: .

1 Like

Have the NPC go to its destination unless there is a nearby player.

Destination =,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
	return closestPlayer

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.
		--Go to its destination

	wait(1) --Time until it tries to find another player to attack

Thank you so much! :heart:

Ill be sure to use this for future scripts.

1 Like