Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Find the player object in the hierarchy
- local FollowPlayer = script.Parent:FindFirstChild("player")
- -- Function to find the nearest player's torso to a given position
- function findNearestPlayerTorso(pos)
- -- Get all players in the game
- local players = game.Players:GetPlayers()
- -- Initialize variables for torso, distance, and temporary storage
- local nearestTorso = nil
- local minDistance = 20 -- Start with a large distance
- -- Iterate through each player
- for _, player in ipairs(players) do
- -- Get the character of the player
- local character = player.Character
- if character then
- -- Find the HumanoidRootPart of the player's character
- local torso = character:FindFirstChild("HumanoidRootPart")
- -- Check if the torso exists
- if torso then
- -- Calculate the distance between the torso and the given position
- local distance = (torso.Position - pos).magnitude
- -- If the distance is shorter than the current shortest distance, update the variables
- if distance < minDistance then
- nearestTorso = torso
- minDistance = distance
- end
- end
- end
- end
- -- Return the nearest player's torso found
- return nearestTorso
- end
- -- Wait for the animation object to load
- local animation = script:WaitForChild("animation1")
- -- Get the humanoid component of the NPC
- local humanoid = script.Parent:WaitForChild('Humanoid')
- -- Load the animation onto the humanoid
- local idle = humanoid:LoadAnimation(animation)
- -- Set the animation to loop indefinitely
- idle.Looped = true
- -- Function to activate the NPC behavior
- local function ActivateNPC()
- while true do
- wait(1) -- Wait for 1 second before each iteration
- -- Find the nearest player's torso to the NPC's HumanoidRootPart position
- local target = findNearestPlayerTorso(script.Parent.HumanoidRootPart.Position)
- -- If a target is found, play the animation and move the NPC's Humanoid to the target's position
- if target then
- idle:Play()
- script.Parent.Humanoid:MoveTo(target.Position)
- else
- -- If no target is found, stop the animation
- idle:Stop()
- end
- end
- end
- -- Function to deactivate the NPC behavior
- local function DeactivateNPC()
- -- Stop the animation
- idle:Stop()
- end
- -- Activate the NPC behavior when the script runs
- ActivateNPC()
- -- Scripted by 1MinuteRobloxTutorials --
Advertisement
Add Comment
Please, Sign In to add comment