Hello! I’ve faced a problem recently with an idea of mine for a “jumpscare”.
What exactly do you want to achieve?
When a player’s camera (or when a player simply sees on their screen) sees an NPC, the NPC will trigger an animation, but it should not trigger when the NPC is behind a wall, more below.
What did you try to do to make it happen/fix issues?
Camera:WorldToViewportPoint
A problem with this is that when I have for an example…
local Vector2Position, isInView = camera:WorldToViewportPoint(monster.PrimaryPart.Position)
if isInView then
-- npc is found, but...
end
it works, HOWEVER, I want to make it so it won’t trigger when the npc is behind a wall, as it triggers when I am looking in the direction of the NPC but there is a wall, massive object, or so. How can I avoid it?
I tried searching, but since I do not know how to properly formate the question I am asking, I was unable to find any results!
You could use ray casting Raycasting | Roblox Creator Documentation, if the ray hits something then the character is behind the wall. (You might have to do a couple rays that are sort of the bound of the character)
Thank you! I actually tried it, but weirdly it triggers it even if I check through raycasting, the code (raycasting part):
-- mons = monster model
for _,v in pairs(mons:GetChildren()) do
pcall(function()
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Whitelist
params.FilterDescendantsInstances = {player.Character}
local ray = workspace:Raycast(cam.CFrame.LookVector,v.Position)
if ray then
print(ray.Instance)
if mons:FindFirstChild(tostring(ray.Instance)) then
-- woohoo we can now proceed ay
canTriggerAction = true
print("ay gotcha")
elseif not mons:FindFirstChild(tostring(ray.Instance)) then
print("behind an object most likely.")
task.wait(.3)
db = false
return
end
end
end)
--if canTriggerAction then break end
end
for _,v in pairs(mons:GetChildren()) do
if v:IsA("BasePart") then
local params = RaycastParams.new()
params.FilterDescendantsInstances = {player.Character}
local ray = workspace:Raycast(cam.CFrame.Position,(v.Position-cam.CFrame.Position).Unit*(v.Position-cam.CFrame.Position).magnitude,params)
if ray then
print(ray.Instance)
if mons:FindFirstChild(tostring(ray.Instance)) then
-- woohoo we can now proceed ay
print("ay gotcha")
elseif not mons:FindFirstChild(tostring(ray.Instance)) then
print("behind an object most likely.")
return
end
end
end
end
In the script, you forgot to add the RaycastParams in the ray and got the origin and the direction wrong.