Yes I had the same issue though didn’t realise it would return the results alphanumerically based on object’s name.
Here is a little bit of code that will always return the closest object by gathering all hit points first where hitx and hity are the closest hit points along the line.
It basically calculates the length of each hit point back to its origin and then calculates which index has the shortest line from the origin(closest).
I have tested it on a recursive function which has generated over 200 raycasts and it has always given what I’m expecting.
local sqrt = math.sqrt local hits = physics.rayCast(fromx,fromy,tox,toy,0) if hits then local totalhits = #hits local smallest local smallesti for i =1,totalhits,1 do local lengthofx = fromx - hits[i].position.x local lengthofy = fromy - hits[i].position.y local totlength = sqrt((lengthofx\*lengthofx)+(lengthofy\*lengthofy)) if i==1 then smallest = totlength smallesti = i elseif i\>1 then if totlength\<smallest then smallest = totlength smallesti = i end end end local hitx = hits[smallesti].position.x local hity = hits[smallesti].position.y end