The methods for finding the closest point and distance between Rays and Vector3 points seem to almost always return incorrect values. I have attached a place file where the bug is happening and my solution.
Thanks for the report! Looks like there are two small things going on here.
First, I think when you call ClosestPoint and Distance methods for a Ray, the Ray itself needs to have unit length, which is not the case when the Ray is created using a direction of v2-v1 (or vice versa). An easy fix is to just replace the calls like r1:ClosestPoint(queryPoint) with r1.Unit:ClosestPoint(queryPoint). The docs do say that ClosestPoint (and by consequence, Distance) need unit Ray’s to work properly, but I agree its not very clear (and is kind of silly in my opinion). I will look into that and see why that is the case.
Second, the Ray’s in Roblox are treated as semi-infinite in the direction specified by Direction. It looks like your distance code was technically finding the closest point in the finite segment between v1 and v2. So there will also be discrepancies in the r1 when the grey ball is moved to the left of the green ball, for instance, but both codes are correct. They are just computing different things.
Thanks this does help me. I didn’t know that the ray needed to be a unit length because this is all I see in Roblox Studio’s script editor when hovering over the function:
Passing a unit ray does solve the issue in my repro file, but in my game I needed it to work with a finite segment so it looks like I would have had to write my own point projecting function if the behavior with non unit vectors was changed anyways.