I made a zombie script for my game. It worked, and I was satisfied with it for a while. The script works by periodically checking where the nearest player is, and moving towards them if they’re within range. However, this causes the zombie to run into the player even if the player is within attacking range, and I don’t like that. I want to make the zombies stop moving when they’re within a certain range of the player. How would I do this? Is there any way to cancel humanoid.MoveTo?
You could check the Magnitude between the player and zombie and if it’s at or below the attack range then stop the MoveTo part of the script.
The issue with that is the moveTo has already been started, and will not stop unless it reaches the place it’s trying to go or times out.
You could stop MoveTo by doing MoveTo(zombie.Position)
So change the script so it updates more often.
This works perfectly, except the zombie turns to face its default direction. How should I solve this? edit: the direction the zombie turns seems random
Check for the magnitude between the player and the mob often and if the value is the same as or lower than your attack distance then you can stop the current MoveTo() running MoveTo() by
Zombie.Humanoid:MoveTo(Zombie.HumanoidRootPart.Position)
Or
local function MoveToClose(humanoid, startPosition, targetPosition, closeEnough)
local vec = targetPosition - startPosition
local mag = vec.Magnitude
local left = mag - closeEnough
if left > 0 then
humanoid:MoveTo(startPosition + left * vec / mag)
end
end
-- when you use it...
while wait(1) do
MoveToClose(
script.Parent.Humanoid,
script.Parent.HumanoidRootPart.Position,
targetPlayer.HumanoidRootPart.Position,
10)
end
Yes, this works, except the zombies sometime seem to turn in a random direction once they reach their goal. Any idea why this might be?
I’m bumping this because I still have no idea what’s going on. When the zombie reaches the player, sometimes the zombie turns in a random direction.
in case anyone’s wondering, I’m not setting the movetopart to anything, so it defaults to nil. I tried setting it to the zombie’s torso, (these zombies don’t have humanoidrootparts) and it worked perfectly but the zombie begins spinning in a circle after the player walks away.
Thanks for your help, I made this work.
Looks like it is something I am looking for. May I ask a question: when do you call MoveToClose function? Is is in Heartbeat/RenderStepped or anywhere else? Thanks.