Advertisement
Pluem1273

Enemy NPC Script

May 27th, 2022
4,175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.05 KB | None | 0 0
  1. local npc = script.Parent
  2. local rightHand = script.Parent.RightHand
  3. local leftHand = script.Parent.LeftHand
  4.  
  5. local isCooldown = false
  6.  
  7. function getClosestPlayer()
  8.     local Closest_player = nil
  9.     local closest_distance = 200
  10.    
  11.     for i, v in pairs(workspace:GetChildren()) do
  12.         if v:FindFirstChild("Humanoid") and v ~= npc then
  13.             local distance = (npc.PrimaryPart.Position - v.PrimaryPart.Position).Magnitude
  14.            
  15.             if distance < closest_distance then
  16.                 Closest_player = v
  17.                 closest_distance = distance
  18.             end
  19.         end
  20.     end
  21.    
  22.     return Closest_player, closest_distance
  23. end
  24.  
  25. function damage(hit)
  26.     if hit.Parent:FindFirstChild("Humanoid") and not isCooldown then
  27.         isCooldown = true
  28.         local humanoid = hit.Parent:FindFirstChild("Humanoid")
  29.        
  30.         humanoid:TakeDamage(20)
  31.        
  32.         wait(0.1)
  33.        
  34.         isCooldown = false
  35.     end
  36. end
  37.  
  38. rightHand.Touched:Connect(damage)
  39. leftHand.Touched:Connect(damage)
  40.  
  41. while wait() do
  42.     local player, distance = getClosestPlayer()
  43.    
  44.     if player and distance > 10 then
  45.         npc.Humanoid:MoveTo(player.PrimaryPart.Position)
  46.     end
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement