When I recently played an SCP game, I was wondering how to make an “NPC that works when you not look at it” like SCP-173 with Roblox,
but I couldn’t find it in various places when I searched for “Detects the orientation of the player’s head nearby and sees if it is looking at itself”. How do you make it? Thank you.
(Although not required, please tell me how to detect the Player closest to the NPC.)
If by “looking at”, you mean facing, them you could use the Vector3:Dot method to determine if the player character’s HumanoidRootPart is facing a target part.
Here is a great simple example of this, taken from this post.
local threshhold = 0 --set this number to the 'percent' at which the object is facing the target (-1 for fully facing away, 1 for completely facing the target); values go for all real numbers between -1 and 1
function ObjIsLookingAtTarget(object,target) --make sure all arguments passed in this function have a CFrame value
local dot = (object.CFrame.LookVector:Dot(target.Position-object.Position).Unit) -- computes the dot product between the object and target
print(dot>=threshhold) -- is the object facing the target?
return dot >= threshhold -- will return a true or false value for later usage
end
You could set the object to Character.HumanoidRootPart, and target to the CPUs HumanoidRootPart, and it would return true or false depending on if the “object”'s front face is facing the “target”.
To find the closest CPU to a Player, you can loop through your CPUs and check the .Magnitude between it and the player to find the closest.
For example:
function FindClosestCPU(Player)
Closest = nil
for _, CPU in pairs(CPUsTable) do
if Closest ~= nil then
if (Player.Character.HumanoidRootPart.Position - CPU.HumanoidRootPart.Position).Magnitude < (Player.Character.HumanoidRootPart.Position - Closest.HumanoidRootPart. Position).Magnitude then
Closest = CPU
end
else
Closest = CPU
end
end
return CPU
end
Hope this is helpful!
Thank you for your reply.
However, I got the “attempt to index number with’Unit’” error in “Vector3.Dot” above. What should i do?
edit : I solved it by deleting the Unit, but I’m not sure what to do with the Player and CPUsTABLE in Player detect script. What should i do?
I’m not exactly sure what you mean by “Player detect script”.
The CPUsTable example was in response to you wanting to find the closest NPC to the Player.
I would recommend keeping a table of all the NPCs in your game in CPUsTable, so you loop through it, as done in my example, to find the closest one.
You could also keep all of the NPCs inside of a folder, and get a table of them using :GetChildren().
CPUsTable = workspace.NPCFolder:GetChildren()
It seems that the script works even if there is a wall in front. how could i fix this?