1MinuteRoblox

Follow only Player Script with Animations V1.0 by 1MinuteRobloxTutorials

Apr 28th, 2024 (edited)
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. -- Find the player object in the hierarchy
  2. local FollowPlayer = script.Parent:FindFirstChild("player")
  3.  
  4. -- Function to find the nearest player's torso to a given position
  5. function findNearestPlayerTorso(pos)
  6. -- Get all players in the game
  7. local players = game.Players:GetPlayers()
  8. -- Initialize variables for torso, distance, and temporary storage
  9. local nearestTorso = nil
  10. local minDistance = 20 -- Start with a large distance
  11. -- Iterate through each player
  12. for _, player in ipairs(players) do
  13. -- Get the character of the player
  14. local character = player.Character
  15. if character then
  16. -- Find the HumanoidRootPart of the player's character
  17. local torso = character:FindFirstChild("HumanoidRootPart")
  18. -- Check if the torso exists
  19. if torso then
  20. -- Calculate the distance between the torso and the given position
  21. local distance = (torso.Position - pos).magnitude
  22. -- If the distance is shorter than the current shortest distance, update the variables
  23. if distance < minDistance then
  24. nearestTorso = torso
  25. minDistance = distance
  26. end
  27. end
  28. end
  29. end
  30. -- Return the nearest player's torso found
  31. return nearestTorso
  32. end
  33.  
  34. -- Wait for the animation object to load
  35. local animation = script:WaitForChild("animation1")
  36. -- Get the humanoid component of the NPC
  37. local humanoid = script.Parent:WaitForChild('Humanoid')
  38. -- Load the animation onto the humanoid
  39. local idle = humanoid:LoadAnimation(animation)
  40. -- Set the animation to loop indefinitely
  41. idle.Looped = true
  42.  
  43. -- Function to activate the NPC behavior
  44. local function ActivateNPC()
  45. while true do
  46. wait(1) -- Wait for 1 second before each iteration
  47. -- Find the nearest player's torso to the NPC's HumanoidRootPart position
  48. local target = findNearestPlayerTorso(script.Parent.HumanoidRootPart.Position)
  49. -- If a target is found, play the animation and move the NPC's Humanoid to the target's position
  50. if target then
  51. idle:Play()
  52. script.Parent.Humanoid:MoveTo(target.Position)
  53. else
  54. -- If no target is found, stop the animation
  55. idle:Stop()
  56. end
  57. end
  58. end
  59.  
  60. -- Function to deactivate the NPC behavior
  61. local function DeactivateNPC()
  62. -- Stop the animation
  63. idle:Stop()
  64. end
  65.  
  66. -- Activate the NPC behavior when the script runs
  67. ActivateNPC()
  68.  
  69. -- Scripted by 1MinuteRobloxTutorials --
  70.  
Advertisement
Add Comment
Please, Sign In to add comment