I was wondering if there is any way I can get the farthest hit on a ray cast. How would I go about achieving this?
Thank you.
I was wondering if there is any way I can get the farthest hit on a ray cast. How would I go about achieving this?
Thank you.
You probably need to use the “sorted” behavior
“any” — Return one result, but not necessarily the closest one.
“closest” — Return only the closest hit from the starting point, if any. This is the default behavior.
“unsorted” — Return all results in no particular order.
“sorted” — Return all results, sorted from closest to farthest.
local hits = physics.rayCast( fromX, fromY, endX, endY, “sorted”)
Then you can go about calling the last value in the table hits. Such as
If hits then farthestHit = hits[#hits] -- since this is a sorted list from closest to farthest, the final value is gonna be the farthest one. end
Or you could go about comparing each hits x or y coordinate with the previous.
Example:-
if hits then local farthest = hits[1] if #hits == 1 then return end for i=2, #hits do if farthest.position.x \< hits[i].position.x then -- You could also go about doing y axis or both depending upon your needs. farthest = hits[i] end end end
I’m just giving you a rough idea on how you could go about finding the farthest hit. The code is not tested, so maybe you can change it according to your needs.
You probably need to use the “sorted” behavior
“any” — Return one result, but not necessarily the closest one.
“closest” — Return only the closest hit from the starting point, if any. This is the default behavior.
“unsorted” — Return all results in no particular order.
“sorted” — Return all results, sorted from closest to farthest.
local hits = physics.rayCast( fromX, fromY, endX, endY, “sorted”)
Then you can go about calling the last value in the table hits. Such as
If hits then farthestHit = hits[#hits] -- since this is a sorted list from closest to farthest, the final value is gonna be the farthest one. end
Or you could go about comparing each hits x or y coordinate with the previous.
Example:-
if hits then local farthest = hits[1] if #hits == 1 then return end for i=2, #hits do if farthest.position.x \< hits[i].position.x then -- You could also go about doing y axis or both depending upon your needs. farthest = hits[i] end end end
I’m just giving you a rough idea on how you could go about finding the farthest hit. The code is not tested, so maybe you can change it according to your needs.