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

what did i do wrong?

Asked by 8 years ago

I'm trying to create an NPC who follow me, however, after he focuses on the player, he does not give up to follow. example: I took him to a place really far, reseted my character, after a minute, I realized that even after I died, he kept following me, and I wanted after I reset myself, he would stop following me :\

players = nil;
dummy = game.Workspace.Dummy;
currentPlayerFollowing = nil;

while wait(1) do
 players = game.Players:GetChildren();

 for i = 0, table.getn(players), 1 do
  if (players[i] ~= nil and (math.abs(players[i].Character.Torso.Position.X - dummy.Torso.Position.X)) <= 10) then
   currentPlayerFollowing = players[i];
  end
 end

 if (currentPlayerFollowing ~= nil) then
    dummy.Humanoid.WalkToPoint = currentPlayerFollowing.Character.Torso.Position
 end
end

1 answer

Log in to vote
0
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

You are only comparing the distance in the x-axis of the player and the NPC. Therefore, it is possible for the NPC to be thousands of studs away in the z-axis but less than 10 away in the x-axis.

To check the linear distance between the two positions, you can use the magnitude of the difference of the two vectors:

local dummy = game.Workspace.Dummy
local following

while wait(1) do
    for _, player in next, game.Players:GetChildren() do
        if (player.Character.Torso.Position - dummy.Torso.Position).magnitude <= 10 then
            following = player
        end
    end

    if currentPlayerFollowing then
        dummy.Humanoid.WalkToPoint = following.Character.Torso.Position
    end
end
Ad

Answer this question