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

How to detect Objects with Raycasting?

Asked by 8 years ago

So i'm working on a project were a ray is pointed and detects what it's on it's way. It's a straight line (theoretically to the infinity) and has amazing hardcoded functions that really helps me out with my project.

So far i got this:

local beam = game.workspace.Beam
local lookVector = beam.CFrame.lookVector
print(lookVector, " LookVector")
local direction = Vector3.new(0, 0, 100)
local ray = Ray.new(lookVector, direction)
print(ray, " (Start - Long)Ray")

local ray = Ray.new(
    lookVector,                           -- origin
    (direction - lookVector).unit * 500 -- direction
) 


local hit, position, normal = game.workspace:FindPartOnRay(ray)
print(hit, " hit ")

if hit.Name == "Part" then
    print("Part!")
else
    print("No Part!")
end

The problem is that, even though "Part" is in front of the beam (on the z line) it says No Part! and the hit value equals Nil. I tested in all directions and still nil.

1 answer

Log in to vote
0
Answered by
cabbler 1942 Moderation Voter
8 years ago

You might not understand how Rays work. A ray is an infinite vector that starts at one position, goes off towards a direction, and can tell you what it hits. Ray.new first takes an origin, which is a position in the world. Giving it the lookvector (a direction) makes no sense. The second argument is a direction (multiplied by a large number for hit detection). "Vector3.new(0,0,100)" is not a direction. And "(direction - lookVector).unit" makes no sense.

If you want a ray from part1 to part2, do this:

local ray = Ray.new(part1.Position, --origin pos
    (part2.Position-part1.Position).unit * 500) --vector from part1 to part2
)

local hit, position, normal = workspace:FindPartOnRay(ray , part1) --ignore part1 so it doesnt' hit itself

If you want a ray towards where a part is looking, not knowing what it will hit, use this ray:

Ray.new(part.Position, part.CFrame.lookVector * 500)

Ad

Answer this question