Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make an attack happen when NPC is in range of a player NOT another NPC?

I am currently working on an NPC script. But I cannot figure out how to make the NPC attack when in range of a player. Help.

local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 200
	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("HumanoidRootPart")
			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




while true do
	wait(math.random(1,5))
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end

end

1 answer

This can be achieved in a plethora of different ways, but the most prominent would be Players:GetPlayerFromCharacter(model).

Learn more about that here.

Your fixed script:

local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")
local players = game:GetService("Players");

function findNearestTorso(pos)
    local list = game.Workspace:children()
    local torso = nil
    local dist = 200
    local temp = nil
    local human = nil
    local temp2 = nil
    for x = 1, #list do
        temp2 = list[x]
        if (temp2:IsA("Model")) and (temp2 ~= script.Parent) and (players:GetPlayerFromCharacter(temp2)) then
            temp = temp2:findFirstChild("HumanoidRootPart")
            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




while true do
    wait(math.random(1,5))
    local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
    if target ~= nil then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    end

end

1 comment

0

What exactly does this do? I want to make an animation play when in range of player. Also, I wanted an attack to play when in range. Using a remote event I wanted to achieve that. Could you help?

This discussion is preserved as it was. New answers, comments, and votes are closed.