How do I make an NPC that runs away from the player when they reach a certain distance?

Hey Cookie Tech,

I’m working on a project where once a player gets within around 50 studs of an NPC (just a normal block rig), the NPC runs in the opposite direction.
Help would be much appreciated. Thanks!

Kind Regards
Joshua

Pathfinding and you can do simple maths to work out how far a player is from the NPC.

You will need to use pathfinding - perhaps look at some models and base your code off of that.

2 Likes

Hey Noah,

What could be a simple script that I could use to use this?
Thank you!

Development Support isn’t for spoonfeeding. Development Support is for fixing issues in scripts or figuring out why a script isn’t working. If you’re able to start on this and you come across an error, we’d be happy to help. :slight_smile:

For this, you could maybe get an NPC that follows you for example, and change it to move away.

Hi there, I realised how silly that was of me. Apologies.
I would just like a little bit of help with the ‘MoveTo:()’ function.
So the entire script is done but I cannot figure out how to make the NPC move away instead of towards. A little bit of help would be appreciated.

Kind Regards,
Josh.

In that case you have solved how to move the player so could you please show us the code handling this?

Hey Noah,
Apologies for the late response. Wi-Fi went down for a long time.
So, I have a script inside of the gun that fires an event which enables the script inside of the NPC. Here’s the gun script:

local runevent = workspace.Events.startrunaway


script.Parent.Equipped:Connect(function()
print("gun equipped")
runevent:Fire()
end)


And here’s the script in the NPC:

local gunequipped = workspace.Events.startrunaway

script.Enabled = false


gunequipped.Event:Connect(function()
	script.Enabled = true
end)

function checkHRP()
	local closest 
	local closestMagnitude = 30
	for index, player in pairs(game.Players:GetPlayers()) do

		if player.Character then
			local hrp = player.Character.HumanoidRootPart
			local hrpMagnitude = hrp and (script.Parent.HumanoidRootPart.Position - hrp.Position).Magnitude
			if closestMagnitude >= hrpMagnitude then
				closestMagnitude = hrpMagnitude
				closest = hrp
			end
		end
	end
	
	return closest
end
local runAwayDistance = 50
while true do
	task.wait()
	local torso = checkHRP()
	if torso then

		script.Parent.Humanoid:MoveTo((CFrame.new(script.Parent.LowerTorso.Position,torso.Position) * CFrame.new(0,0,runAwayDistance)).Position)
		script.Parent.Humanoid.MoveToFinished:Connect(function()

		end)
	end
end

The script isn’t working and just keeps the script enabled. I believe it’s looping in some sort of way? Help would be greatly appreciated. Thanks.

Kind Regards, Josh.

Are there any errors listed in the console?