Raycast ray ends at certain Y-Axis

Im new to using rays in roblox so excuse me if i’m asking for something basic.

I’m using rays to get the position of wherever the ray ends, either by hitting something or being at its maximum distance away.

Heres a diagram of what I want basically, I want the ray to end when the it passes 0 on the Y-Axis or when it hits something. The alternative I’ve tried would be hard to work with in the actual game considering the worldspace being so large.

1 Like

I believe something like this should work (untested)

local origin = Vector3.new(...)
local direction = Vector3.new(...)

direction = direction.Unit -- make sure direction is a unit vector (length = 1)

local heightPerUnit = direction.Y -- how far down ray goes per unit

if heightPerUnit >= 0 then
    warn("Ray is pointed up, will never reach Y=0")
    return
end

local length = origin.Position.Y / -heightPerUnit -- length of ray to reach Y=0

local result = workspace:Raycast(origin, direction * length)
1 Like

Whether or not this is enough depends on whether his rays all have their origin above y=0 as in his diagram. If the rays can start below the y=0 plane, you have to generalize this check to account for both cases.

The other option you have, beside pre-computing the ray length, is to do a max length raycast and just ignore the raycast result if the result.Position.Y is on the opposite side of the y=0 plane from the ray origin (proceed like nothing was hit).

1 Like

Depending on the scale of your project, you could try adding an invisible part, rescaling it the way you see fit, and positioning it at Y = 0. Then set the Transparency to 1 and turn off CanCollide and CanTouch, but keep CanQuery set to true. Now we have an invisible part that can’t be interacted with in any way other than a raycast.

From here you can simply do:

if rayResult then
	if rayResult.Instance == (your part) then return end
end

Another approach is to simply detect the ray.Position’s Y-value and end the function if it is less than 0.

1 Like

Unless the ray hits an object, it returns result.Position as nil.
I forgot to mention that the objects position is behind the mouse, hard to explain so heres another example that should’ve been included with the original post.

better

Basically the part appears behind the mouse while also being at y=0 (or a determined Y value)

Like this:

if the result is equal to null then you can get the position by getting the part’s lookvector multiplying by the distance.

example:

if not result then
position = part.CFrame.LookVector * length
end

image

This returns a position that isnt in the desired position.
Not to mention its locked to move on the Z-axis

place a decal on the part and change the face to front then rotate the part towards the direction you want it to point to

I can’t seem to get that to work right now so i’d prefer to work with raycasts. But if I manage to get this working i’ll let you know

I’m not very good with CFrames.