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

Detecting objects within first person view using Rays, how?

Asked by 10 years ago

I plan on creating a method that will detect when certain objects are within your sight (On your screen, so to speak.). It is important to note that my game will be in a permanent First Person View state, so I have created a Ray, who's origin is the characters head, and the direction is the heads lookVector. Anyway, using that Ray it was easy for me to detect what object I am staring at right INFRONT of me, but it will not detect the objects in the places my mouse is not pointing at. Do you understand? What I want is that somehow, with Rays or without, i'll be able to detect whether or not a certain object is within the players sight. Thank's in advance!

0
This question requires a really complex solution for optimal speed. Tomorrow, I'm going to make a place for you to see actual code in, then link it here as an Answer with some explanations as to how it works. It's really late for me right now, sorry. adark 5487 — 10y
0
That'd be nice :O NutsNWaffles 135 — 10y

1 answer

Log in to vote
2
Answered by
wazap 100
10 years ago
local listOfItems = {workspace.Object1, workspace.Object2}
repeat wait() until game.Players.LocalPlayer.Character
local head = game.Players.LocalPlayer.Character.Head
local AngleOfSight = 15 --Everything within 15 degrees will be seen
function inSight(hitPos, headPos)
    local scan = head.CFrame.lookVector
    local vect = hitPos-headPos
    return  math.acos((vect.X*scan.X+vect.Y*scan.Y+vect.Z*scan.Z)/vect.magnitude)<AngleOfSight
end

while wait() do
    local itemsInSight = {}
    local startPos = head.Position
    for i, v in pairs(listOfItems) do
        local ray = Ray.new(head.Position, (v.Position-head.Position).unit*999)
        local cast, hit = workspace:FindPartOnRay(ray, head.Parent)
        if cast and cast == v and inSight(hit, startPos) then
            table.insert(itemsInSight, v)
        end
    end
end
0
I'll check this soon enough, however I would like you to explain what you did on line 8, thanks! NutsNWaffles 135 — 10y
0
Worked just fine when I set the AngleOfSight to 1. Thanks! Though I would still like to know what you did on line 8. NutsNWaffles 135 — 10y
0
Its math. If the item is within the angle range, it'll return true, otherwise it'll return false wazap 100 — 10y
Ad

Answer this question