Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Making an enemy always have a distance from the player?

Issue: My script can already follow the player wherever it goes, it just looks like its hugging the player at all times.

Goal: Make a script to keep the enemy away from the player but still follow the player.

Script to follow the player:

local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end




while true do
	wait(1)
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end

end

Thanks

1 answer

✓ Accepted answer

Here's a function that will get you the closest position to the player based off the units position while maintaining a distance. I didn't test out this script so if it doesn't work lmk or try and fix it yourself.

--unitPos is the position of the unit, while plrPos is the position of the player
--dist is the distance you want to keep from the player
local function getMovePos(unitPos, plrPos, dist)
	local offset = CFrame.new(plrPos, unitPos).LookVector.Unit * dist
	return plrPos+ offset
end

This discussion is preserved as it was. New answers, comments, and votes are closed.