Raycasting Help

Say I make a raycast and get the data from it like so:

local ray = Ray.new(origin, direction)
local hitPart, hitPosition = workspace:FindPartOnRay(ray, origin)

If the origin was 10 or less studs away, it would move, but if not it would stay.
How would I let the script know if the origin was 10 or less studs away from the “hitPart”?

this old method is deprecated, use the new workspace:Raycast() instead of findpartonray, also you put local local instead of local, and what is the “origin”, you can use ToObjectSpace to get the distance or use the unit * distance

I understand this method is deprecated. Origin is a placeholder for the part it starts from.

Is there a way to get the distance using the current method I am using?

I believe this is a vector math problem.

So to measure the distance between the origin and the hit position in the example scenario you can do this:

--Vector travels from origin of where ray is cast to the hit position
local travelVector = hitPosition - origin
--Get's the distance
print(travelVector.Magnitude)
1 Like

I will test this out! Thanks for the reply!

1 Like

If I wanted to see if it were ten studs away, would I do:

if travelVector.Magnitude <= 10 then
--code
end

Or is there some different way?

Yep thats one way to do it. Keep in mind that the Vector3.Magnitude can be fairly resource intensive as it performs sqrt(x^2 + y^2 + z^2) math as explained in this topic:

2 Likes

Your explanations are splendid! They really helped a lot! Thank you so so much!

1 Like