How do I make something run away from a player when they get too close?

So, I’m trying to make a small fox run away from you when you touch an invisible part surrounding said fox. Unfortunately, I have not been successful in my attempts at making it work. None of the other topics I have viewed resolve my issue. Does anybody have any solutions? If so, I would appreciate it a lot.

The script that I’ve tried looks something like this:

local fox = script.Parent

local run = fox:FindFirstChild(“RUN”)
local hearing1
local hearing2
local hearing3 = fox:FindFirstChild(“Hearing3”)

local chance1
local chance2
local chance3

local debounce = false

hearing3.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
if debounce == false then
debounce = true
chance3 = math.random(2, 3)
print(tostring(chance3))
if chance3 == 2 then
fox.Humanoid.WalkSpeed = 20
run.Value = true
fox.Humanoid:MoveTo(Vector3.new(player.Character.Humanoid.MoveDirection * -1))
wait(5)
debounce = false
run.Value = false
fox.Humanoid.WalkSpeed = 10
else
wait(1)
debounce = false
end
end
end
end)

Please help! I am completely lost. That script above moves the fox to some random location on the map, regardless of what direction the player is facing.

You can use the positions of the fox and the player to find a direction to move in, and use :Move() to set a direction to move in instead of a position to move towards.

local direction = (player.Character.HumanoidRootPart.Position - fox:GetPivot().Position)
fox.Humanoid:Move(direction)

Thank you! I modified the script and multiplied it by -1 in order to get it to run away from the player, but it still got rid of the issue.

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