Hello lads Me and my mate are working on a game but have been having trouble with scripting the npc's. We have tried this script but the npc's either attack other npc's or do nothing at all. Was wondering if anybody here may be able to help us out. We are new to this and would really appreciate the help.
We need the npc to only attack the players To be able to spot the players from 40 studs away (not sure how to do this) and to do 10 damage to the player upon impact
also is it possible to get the npc to respawn 20 seconds after being killed? or does this have to be done separately in a npc spawner?
please feel free to ask any questions
thank you in advance.
Here is the follow script i have tried, either follows npcs or does nothing at all.
function findNearestTorso(pos) local list = game.Workspace:children() local torso = nil local dist = 1000 local temp = nil local human = nil local temp2 = nil for x = 1, #list do temp2 = list[x] if (temp2.className == "Model") and (temp2 ~= script.Parent) then temp = temp2:findFirstChild("Torso") human = temp2:findFirstChild("Humanoid") if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then if (temp.Position - pos).magnitude < dist then torso = temp dist = (temp.Position - pos).magnitude end end end end return torso end --wait(math.random(0,5)/10) while true do wait(0.5) local target = findNearestTorso(script.Parent.Torso.Position) if target ~= nil then script.Parent.Humanoid:MoveTo(target.Position, target) end end
A far better way to do this is to cycle through all characters given the player and find the nearest torso instead of looping through workspace. Using this method you will only target players, and it is much faster/efficient.
local distance = 0; local target; for _, player in pairs(Players:GetPlayers()) do --get all players local thisDistance = (script.Parent - player.Character:WaitForChild("HumanoidRootPart")).Magnitude; if thisDistance < distance then --check if current rootpart is closer distance = thisDistance; target = player.Character; end end
The code above is what should go in your function for finding the closest player, and solves your problem for erratic target assigning behaviour
Notice I get the distance from the rootpart instead of the torso, because with different kinds of avatars you can have the uppertorso or just the torso, but there will always be a humanoidrootpart. Furthermore, change the script.Parent in the magnitude parentheses to whatever part you want on the enemy that's best to gauge the difference.
Good luck with your game!