Advertisement
HowToRoblox

MobSpawner

Jan 14th, 2023 (edited)
2,455
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 7.75 KB | None | 0 0
  1. local rs = game:GetService("ReplicatedStorage")
  2. local mobs = rs:WaitForChild("Mobs")
  3.  
  4. local mobSpawners = workspace:WaitForChild("MobSpawns")
  5.  
  6. local rand = Random.new()
  7.  
  8. local ps = game:GetService("PhysicsService")
  9.  
  10. local mobsCG = "Mobs"
  11. local charsCG = "Characters"
  12.  
  13. ps:RegisterCollisionGroup(mobsCG)
  14. ps:RegisterCollisionGroup(charsCG)
  15.  
  16. ps:CollisionGroupSetCollidable(mobsCG, charsCG, false)
  17.  
  18. local respawnTime = 3
  19. local maxDistanceCanMoveFromSpawn = 15
  20.  
  21.  
  22. function calculateRandomPosition(originPosition:Vector3)
  23.    
  24.     local randomOffset = rand:NextNumber(5, maxDistanceCanMoveFromSpawn)
  25.     local randomX = rand:NextNumber(0, randomOffset)
  26.     local randomZ = math.sqrt(randomOffset^2 - randomX^2)
  27.  
  28.     local newPosition = originPosition + Vector3.new(randomX, 0, randomZ)
  29.    
  30.     return newPosition
  31. end
  32.  
  33.  
  34. function handleSpawner(spawner:Part)
  35.    
  36.     local typeOfMob = spawner.Name
  37.    
  38.     if mobs:FindFirstChild(typeOfMob) then
  39.    
  40.         local spawnerCF = spawner.CFrame
  41.        
  42.         local newMob = mobs[typeOfMob]:Clone()
  43.        
  44.         for _, descendant in pairs(newMob:GetDescendants()) do
  45.             if descendant:IsA("BasePart") then
  46.                 descendant.CollisionGroup = mobsCG
  47.             end
  48.         end
  49.  
  50.         local mobConfig = newMob:WaitForChild("Configuration")
  51.        
  52.         local mobAnims = newMob:WaitForChild("Animations")
  53.         local animTracks = nil
  54.        
  55.         local mobHumanoid = newMob:WaitForChild("Humanoid")
  56.         local mobRoot = newMob:WaitForChild("HumanoidRootPart")
  57.        
  58.         local mobHealthBar = rs:WaitForChild("HealthBar"):WaitForChild("HealthBarGui"):Clone()
  59.         mobHealthBar.StudsOffset = Vector3.new(0, newMob:GetExtentsSize().Y * 0.6, 0)
  60.         mobHealthBar.Enabled = false
  61.         mobHealthBar.Parent = newMob.HumanoidRootPart
  62.        
  63.         mobHumanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
  64.         mobHumanoid.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff
  65.        
  66.         mobHumanoid.MaxHealth = 1000000
  67.         mobHumanoid.Health = 1000000
  68.        
  69.         mobHumanoid.WalkSpeed = mobConfig:WaitForChild("WalkSpeed").Value
  70.        
  71.         mobHumanoid.HealthChanged:Connect(function(newHealth)
  72.            
  73.             local damageDealt = mobHumanoid.MaxHealth - newHealth
  74.            
  75.             mobConfig:WaitForChild("CurrentHealth").Value -= damageDealt
  76.            
  77.             mobHumanoid.Health = mobHumanoid.MaxHealth
  78.         end)
  79.        
  80.        
  81.         while true do
  82.            
  83.             mobConfig:WaitForChild("CurrentHealth").Value = mobConfig:WaitForChild("MaxHealth").Value
  84.            
  85.             newMob.Parent = workspace
  86.             mobRoot.CFrame = spawnerCF
  87.            
  88.             if not animTracks then
  89.                 animTracks = {}
  90.                
  91.                 for _, anim in pairs(mobAnims:GetChildren()) do
  92.                    
  93.                     local newTrack = mobHumanoid:WaitForChild("Animator"):LoadAnimation(anim)
  94.                     animTracks[anim.Name] = newTrack
  95.                 end
  96.             end
  97.            
  98.             local lastAttacked = 0
  99.            
  100.             local goalRandomPosition = nil
  101.            
  102.             while true do
  103.                
  104.                 if (mobConfig:WaitForChild("CurrentHealth").Value ~= mobConfig:WaitForChild("MaxHealth").Value) then
  105.                    
  106.                     mobHealthBar.MobName.Text = newMob.Name
  107.                     mobHealthBar.BarBackground.Health.Text = mobConfig.CurrentHealth.Value .. "/" .. mobConfig.MaxHealth.Value
  108.                     mobHealthBar.BarBackground.Bar.Size = UDim2.new(mobConfig.CurrentHealth.Value / mobConfig.MaxHealth.Value, 0, 1, 0)
  109.                    
  110.                     mobHealthBar.Enabled = true
  111.                    
  112.                 else
  113.                     mobHealthBar.Enabled = false
  114.                 end
  115.                
  116.                 if (not animTracks.Idle.IsPlaying) then
  117.                     animTracks.Idle:Play()
  118.                 end
  119.                
  120.                 local v = mobRoot.AssemblyLinearVelocity * Vector3.new(1, 0, 1)
  121.                
  122.                 if (v.Magnitude > 0.1) and (not animTracks.Walk.IsPlaying) then
  123.                     animTracks.Walk:AdjustSpeed(mobHumanoid.WalkSpeed / 8)
  124.                     animTracks.Walk:Play()
  125.                    
  126.                 elseif (v.Magnitude <= 0.1) and (animTracks.Walk.IsPlaying) then
  127.                     animTracks.Walk:Stop()
  128.                 end
  129.                
  130.                 local players = game:GetService("Players"):GetPlayers()
  131.                 local closestCharacterInRange = nil
  132.                
  133.                 for _, player in pairs(players) do
  134.                    
  135.                     local character = player.Character
  136.                     if (character) and (character:FindFirstChild("Humanoid")) and (character.Humanoid.Health > 0) then
  137.                        
  138.                         for _, descendant in pairs(character:GetDescendants()) do
  139.                             if descendant:IsA("BasePart") then
  140.                                 descendant.CollisionGroup = charsCG
  141.                             end
  142.                         end
  143.                        
  144.                         local mobPos = mobRoot.Position
  145.                         local charPos = character.HumanoidRootPart.Position
  146.                        
  147.                         local raycastParams = RaycastParams.new()
  148.                         raycastParams.FilterDescendantsInstances = {newMob, character}
  149.                         local lineOfSight = not workspace:Raycast(mobPos, charPos, raycastParams)
  150.                        
  151.                         local distanceFrom = (mobPos - charPos).Magnitude
  152.                         local maxDistanceAllowed = mobConfig:WaitForChild("DetectionRange").Value
  153.                        
  154.                         if (lineOfSight) and (distanceFrom <= maxDistanceAllowed) then
  155.                            
  156.                             if (not closestCharacterInRange) then
  157.                                 closestCharacterInRange = {character, distanceFrom}
  158.                             elseif (distanceFrom < closestCharacterInRange[2]) then
  159.                                 closestCharacterInRange = {character, distanceFrom}
  160.                             end
  161.                         end
  162.                     end
  163.                 end
  164.                
  165.                
  166.                 if (closestCharacterInRange) then
  167.                     mobHumanoid:MoveTo(closestCharacterInRange[1].HumanoidRootPart.Position)
  168.                    
  169.                     local attackCooldown = mobConfig:WaitForChild("AttackCooldown").Value
  170.                    
  171.                     local canAttack = (tick() - lastAttacked) >= attackCooldown
  172.                     if (canAttack) then
  173.                        
  174.                         local attackRange = mobConfig:WaitForChild("AttackRange").Value
  175.                         local inAttackRange = (closestCharacterInRange[2]) <= attackRange
  176.                        
  177.                         if (inAttackRange) then
  178.                             mobRoot:WaitForChild("AttackSound"):Play()
  179.                            
  180.                             local raycastParams = RaycastParams.new()
  181.                             raycastParams.FilterDescendantsInstances = {newMob}
  182.                            
  183.                             local raycast = workspace:Raycast(mobRoot.Position, mobRoot.CFrame.LookVector * mobConfig.AttackRange.Value, raycastParams)
  184.                            
  185.                             local targetHumanoid = raycast and (raycast.Instance.Parent:FindFirstChild("Humanoid") or raycast.Instance.Parent.Parent:FindFirstChild("Humanoid"))
  186.                             if (targetHumanoid) and (game.Players:GetPlayerFromCharacter(targetHumanoid.Parent))  then
  187.  
  188.                                 task.spawn(function()
  189.                                     task.wait(0.4)
  190.                                     targetHumanoid:TakeDamage(mobConfig:WaitForChild("Damage").Value)
  191.                                 end)
  192.                             end
  193.                            
  194.                             animTracks.Attack:Play()
  195.                            
  196.                             mobRoot.AssemblyLinearVelocity = mobRoot.CFrame.LookVector * Vector3.new(60, 0, 60) + mobRoot.CFrame.UpVector * 6
  197.                            
  198.                             lastAttacked = tick()
  199.                         end
  200.                     end
  201.                    
  202.                 else
  203.                    
  204.                     local originPosition = spawnerCF.Position
  205.                    
  206.                     if (goalRandomPosition) and (typeof(goalRandomPosition) == "Vector3") then
  207.                         mobHumanoid:MoveTo(goalRandomPosition)
  208.                        
  209.                         if ((goalRandomPosition - mobRoot.Position).Magnitude <= 5) or (mobRoot.AssemblyLinearVelocity.Magnitude < 0.1) then
  210.                             goalRandomPosition = nil
  211.                         end
  212.                        
  213.                     elseif (goalRandomPosition) then
  214.                        
  215.                         if ((tick() - goalRandomPosition[1]) >= goalRandomPosition[2]) then
  216.                             goalRandomPosition = nil
  217.                         end
  218.                        
  219.                     else
  220.                        
  221.                         local moveToNewSpot = rand:NextNumber()
  222.                        
  223.                         if (moveToNewSpot > 0.5) then
  224.                             goalRandomPosition = calculateRandomPosition(originPosition)
  225.                            
  226.                         else
  227.                             goalRandomPosition = {tick(), rand:NextNumber(1, 5)}
  228.                         end
  229.                     end
  230.                 end
  231.                
  232.                
  233.                 if (mobConfig.CurrentHealth.Value <= 0) then
  234.                     break
  235.                 end
  236.                
  237.                 task.wait(0.05)
  238.             end
  239.            
  240.             newMob.Parent = game:GetService("ServerStorage")
  241.            
  242.             task.wait(respawnTime)
  243.         end
  244.        
  245.        
  246.     else
  247.         warn("Mob of type\n" .. typeOfMob .. "\n was not found. Make sure you spelled the name properly for the spawner part.")
  248.     end
  249. end
  250.  
  251.  
  252. for _, spawner in pairs(mobSpawners:GetChildren()) do
  253.     task.spawn(handleSpawner, spawner)
  254. end
  255.  
  256. mobSpawners.ChildAdded:Connect(function(child)
  257.     task.spawn(handleSpawner, child)
  258. end)
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement