Getting Distance to a Part Using a Ray

Currently, I’m working on a building system, and I have an issue where I’m raycasting in order to detect which section of the build grid I hit. However, in order to not lag too much when using Instance.new, I created only a few parts. However, I need to get the distance between the hit part, and the ray’s origin. This is an issue because:

A. Using the magnitude of the part will return the distance to the center
B. I need to calculate the endpoint of the ray as to where it was hit, but I’m unsure of how to do this
C. I simply need to know someway to get what point in the ray was there a part

Any help is appreciated!

1 Like

This will give you the distance from where the Ray started, to where it hit.
If the ray does not hit something, the RayResult will be nil.

(rayResults.Position-rayOrigin).Magnitude
3 Likes

This did work. However, I still have some confusion. Why does this not return the center of the part?

It will return the Position of where the Ray hit, if you want the center of a part, just do part.Position

1 Like

So rayResult doesn’t use the Instance’s properties, It just returns a point of where the ray hit?

These are what is returned in the RayResult

RaycastResult.Position would be where the Ray hit the part, if it did hit the part.

2 Likes