I want to check if player is looking at NPC. This script doesn’t seem to work. It is my first time using WorldToScreenPoint.
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
local character = v:findFirstChildOfClass("Humanoid").Parent
if character.Humanoid then
if character.Humanoid.Health > 0 then
if (character.Head.Position - script.Parent.HumanoidRootPart.Position).magnitude < 60 then
local onScreen = camera:WorldToScreenPoint(script.Parent.HumanoidRootPart.Position)
if onScreen then
looking = true
else
looking = false
end
end
end
end
end
end
That is because :WorldToScreenPoint() returns 2 things.
A vector that represents the offset from the top left corner of the screen.
And then a bool value that tells whether it’s on screen or not.
You haven’t put the onScreen variable in the right order.
Use:
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
local character = v:findFirstChildOfClass("Humanoid").Parent
if character.Humanoid then
if character.Humanoid.Health > 0 then
if (character.Head.Position - script.Parent.HumanoidRootPart.Position).magnitude < 60 then
local vector, onScreen = camera:WorldToScreenPoint(script.Parent.HumanoidRootPart.Position)
if onScreen then
looking = true
else
looking = false
end
end
end
end
end
end
I have basically put onScreen in the right order (as the secondary variable).
I have changed the script a bit and now it always prints false, no matter what.
Note: server script is a child of NPC.
game.Players.PlayerAdded:Connect(function(player)
while wait(0.1) do
print(looking)
looking = false
wait(0.1)
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
local character = v:findFirstChildOfClass("Humanoid").Parent
if character.Humanoid and character ~= script.Parent and character ~= player.Character then
if character.Humanoid.Health > 0 then
local vector, onScreen = camera:WorldToScreenPoint(script.Parent.HumanoidRootPart.Position)
if onScreen then
print(character.Name)
looking = true
else
looking = false
end
end
end
end
end
end
end)