I was practicing some AI stuff, so I made this script: (serverscript inside of the actual npc)

local humanoid = script.Parent.Humanoid
local hrp = script.Parent.HumanoidRootPart
local enemyChar
function wander()
	humanoid.WalkSpeed = 8
	humanoid:MoveTo(hrp.Position + Vector3.new(math.random(-5,5),0,math.random(-5,5)))
end
function getDistance(target1,target2)
	return (target1.Position - target2.Position).Magnitude
end
function findTarget()
	for i,v in pairs(workspace:GetChildren()) do
		if v:FindFirstChild("Humanoid") and getDistance(hrp,v.PrimaryPart) <= 50 and not v:FindFirstChild("Husk") then
			return v
		end
	end
	return nil
end

while true do
	wander()
	if findTarget() then
		enemyChar = findTarget()
		humanoid.WalkSpeed = 24
		humanoid:MoveTo(enemyChar.PrimaryPart.Position)
		humanoid.MoveToFinished:Wait(1)
	end
	wait()
end

It works well and all, but for some reason the npc keeps stopping for a split second, then starts walking again.

Also, am I using the while loop incorrectly? I feel like that's going to cause some performance issues...

Any help is appreciated!

4 comments

0

Yea, most people reccomend not using "while true do" loops if it can be avoided. Try some sort of event so its better synced with the server, though I cant think of one off the top of my head.

0

Alright, I'll see what I can think of.

0

It is your line 26, remove :Wait(1) and put :Wait()

0

Oh ok