[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

## Is there any way to get the farthest hit of a raycast? Started by Blex Dec 20 2018 03:35 PM

1 reply to this topic
[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

### Blex

[GLOBAL: userInfoPane.html]
Blex
• Corona Geek

• 1,199 posts
• Corona SDK

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.

[TOPIC: post.html]
#2

### Quitalizner

[GLOBAL: userInfoPane.html]
Quitalizner
• Enthusiast

• 45 posts
• Corona SDK

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.

[topic_controls]

[/topic_controls]