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

How do I make NPC head look at player?

I want make NPC head look at the closest to it player so the NPC seem real !

2 answers

This would go into a the NPC's head:

while true do
local part1 = game.Workspace.NPC.head -- replace with NPC's head
local closest = 100  --so we can make sure that it gets a value
for _,player in pairs(game.PLayers:getPLayers()) do
	local dis = (part1 - player.UpperTorso).Magnitude
	if dis < closest then
		local part2 = player.UpperTorso -- look at the torso
		closest = dis
	end
end

part1.CFrame = CFrame.new(part1.Position, part2.Position)
wait() --smoother movement
end

5 comments

0

Sorry if this doesn't help

0

This will not work

0

Why?

0

Sorry Let me fix this

0

Add a special mesh into the head of the NPC and if you haven't add a humanoid to it.

Here's a script that should work for you. Put this in a Script inside your NPC.

--Get services
local Players = game:GetService("Players")

--Find the head or warn that the NPC does not have a head
local Head = script.Parent:FindFirstChild("Head") or error(script.Name .. " does not have head!")
while #Players:GetPlayers() > 0 do
	local closest = math.huge
	local lookAt

	--Let's check all of the players
	for i,player in pairs(Players:GetPlayers()) do
		--Make sure the player is in the world, because if its not, it will say its 0 studs away, which is not what we want!
		if player.Character and player.Character:FindFirstChild("Head") then
			local distance = player:DistanceFromCharacter(Head.Position)
			if distance < closest then
				--This player was closer than the last one
				closest = distance
				lookAt = player.Character.Head
			end
		end
	end
	--Look at the player we found. This method will only work if the NPC is anchored. If not, please comment, I'll revise the script.
	Head.CFrame = CFrame.new(Head.Position, lookAt.Position)
	--Add a delay in between running the script. 1/x, where x is how many times you want it to update a second. Higher numbers for smoother head turning, but less lag.
	wait(1/10)
end

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