Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

why doesn't this NPC move towards the player after he dies?

Asked by 5 years ago
Edited 5 years ago

I made an NPC that follows you to kill you, but when you kill it, you respawn, and ten seconds later he respawns, but he stops following you. I think it has to do with the game.Players.PlayerAdded function but that is the only way I know. The script is inside the NPC

game.Players.PlayerAdded:Connect(function(p)
p.CharacterAdded:Connect(function(char)
while true do
wait(0.1)
if p:DistanceFromCharacter(script.Parent.HumanoidRootPart.Position) < 90 then
script.Parent.Humanoid:MoveTo(char.HumanoidRootPart.Position)
end
end
end)
end)
0
When a player resets, their character disappears. So whenever the NPC tries to follow the character, the character is nil. DeceptiveCaster 3761 — 5y
0
If that's the problem, then how can I make it so that the character is not nil when the player respawns Boi52893642864912 69 — 5y
0
p:WaitForChild("Character") DeceptiveCaster 3761 — 5y
0
I tried that and p.Character but they both don't work Boi52893642864912 69 — 5y
View all comments (6 more)
0
You can instead check if the HumanoidRootPart is nil: if p.Character:FindFirstChild("HumanoidRootPart") then DeceptiveCaster 3761 — 5y
0
Okay so now it detects the HumanoidRootPart but he won't move Boi52893642864912 69 — 5y
0
Do this: script.Parent.Humanoid:MoveTo(char.HumanoidRootPart.Position, char.HumanoidRootPart) DeceptiveCaster 3761 — 5y
0
MoveTo() on the Humanoid has two parameters. The first is the point (Vector3) the Humanoid is trying to walk to, and the second is the part that's it's trying to walk to. DeceptiveCaster 3761 — 5y
0
It doesn't seem to want to do anything Boi52893642864912 69 — 5y
0
Oh, now I see. DistanceFromCharacter() is always calculating below 90 because the character being reset, which means that it's constantly calculating 0. And because the Character is nil when that condition is met, the NPC never moves. You have to check if the distance is above 0 before moving the NPC. DeceptiveCaster 3761 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago
function ready(tmp_plr)
game:GetService("RunService").Stepped:connect(function()
local yes, error = ypcall(function()
if (math.abs((tmp_plr.Character.Head.Position-script.Parent.Head.Position).magnitude)) < 90) then
script.Parent.Humanoid:MoveTo(tmp_plr.Character.Head.Position)
end
end)
end)
end    
game.Players.PlayerAdded:Connect(function(p)
ready(p)
end)
0
Using RunService won't break the code if there's an error, further ypcall protects any errors from breaking the code. You only need to call the function once and that is when the player is added. NeonProfile 111 — 5y
0
I'm sorry, why are you breaking the error function? DeceptiveCaster 3761 — 5y
Ad

Answer this question