How to do i prevent my NPC from shooting multiple targets at once?
Im making a star wars game and my battle droid is supposed to fire its blaster at the closest target it can find, however if there are multiple targets in its range it will fire at all of them at once. How can i prevent this from happening. I understand why its happening but how can i prevent it?
Here is a video link to show whats i mean:
https://screencast-o-matic.com/watch/c3V6VQVoT5t
Here is the code that makes it fire:
02 | local parentTorso = script.Parent.Parent.Parent:WaitForChild( "Torso" ) |
03 | local origin = script.Parent |
04 | local gun = script.Parent.Parent |
05 | local selfHuamn = script.Parent.Parent.Parent.Humanoid |
11 | for i,v in pairs (game.Workspace:GetChildren()) do |
12 | local human = v:FindFirstChild( "Humanoid" ) |
13 | local torso = v:FindFirstChild( "Torso" ) |
14 | if human and torso and torso ~ = parentTorso and (parentTorso.Position - torso.Position).magnitude < = agroDist then |
15 | print ( "player found near by" ) |
17 | if target = = torso and human.Health > 0 and selfHuamn.Health > 0 then |
19 | origin.CFrame = CFrame.new(origin.Position, torso.Position) |
20 | local laser = Instance.new( "Part" , parentTorso) |
21 | laser.Size = Vector 3. new(. 2 ,. 2 , 6 ) |
22 | laser.Anchored = false |
23 | laser.CanCollide = false |
24 | laser.BrickColor = BrickColor.new( "Really blue" ) |
25 | laser.Material = "Neon" |
26 | laser.CFrame = origin.CFrame * CFrame.new( 0 , 0 , 0 ) |
28 | local bodyV = Instance.new( "BodyVelocity" , laser) |
29 | bodyV.MaxForce = Vector 3. new( math.huge , math.huge , math.huge ) |
30 | bodyV.Velocity = origin.CFrame.LookVector * 150 |
32 | laser.Touched:Connect( function (hit) |
33 | local human = hit.Parent:FindFirstChild( "Humanoid" ) |
35 | human.Health = human.Health - 5 |