Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I make NPC head look at player? [closed]

Asked by 4 years ago

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

Closed as Not Constructive by hiimgoodpack

This question has been closed because it is not constructive to others or the asker. Most commonly, questions that are requests with no attempt from the asker to solve their problem will fall into this category.

Why was this question closed?

2 answers

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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
0
Sorry if this doesn't help marine5575 359 — 4y
0
This will not work zemljorog 80 — 4y
0
Why? marine5575 359 — 4y
0
Sorry Let me fix this marine5575 359 — 4y
0
Add a special mesh into the head of the NPC and if you haven't add a humanoid to it. ivan08pr -3 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

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