How do I raycast towards a target?

My goal is basically to raycast from one part to another. This is to check if there is something interrupting the view of two parts. I know that when raycasting, the first argument is the origin (so the part’s position) and the second argument is the direction it shoots in?

So how exactly would I get this to shoot a line directly from one part to another part? Is there some crazy math? Am I just stupid?

The algorithm for getting a direction is:

(endpoint - startpoint).Unit

It’s normalized (using the Unit property) to give it a length of 1, so you can scale it to be any length.

So implementing it, you’d have something like:

local rayLength = 15 --//How long the ray should be

local rayOrigin = part1.Position
local rayDirection = (part2.Position - part1.Position).Unit * rayLength

local rayResult = workspace:Raycast(rayOrigin, rayDirection)
1 Like

what is the “unit” propert exactly?

It returns the same direction but with a length of 1, so it’s scaled down basically, giving you a vector that you can multiply to the length that you need it to be.

If you use the raw direction vector, you’re not going to get the results you’re anticipating. Depending on how far those parts are away from each other, you could get dramatically different results each time.

So using unit insures the length is the same every single time, so only the direction is what’s different.

Is the length always going to be to the exact position of the target part?

The length of the vector will always be no greater than 1. The direction will be correct, it’s just scaled down.

oh so it should look like that.unit * raylength which is what you said very cool

so should rayLength be like part2.position - part1.position.magnitude?

That’s exactly what it should be, just with the parentheses.

(part2.Position - part1.Position).Magnitude