I want to use the ordering of objects ray hits in RaycastResult array. But the order of the objects in the array comes randomly. Is there any method to solve this problem?

Sample project (Press R for ray) → PlayCanvas | HTML5 Game Engine

I want to use the ordering of objects ray hits in RaycastResult array. But the order of the objects in the array comes randomly. Is there any method to solve this problem?

Sample project (Press R for ray) → PlayCanvas | HTML5 Game Engine

Unfortunately, you will have to sort the results yourself base on you own criteria, eg distance.

1 Like

Thanks @yaustar, I will solve it like this. But having this feature by itself can be a useful update.

When the API was originally designed, we decided not to sort it because not everyone needs actual needs it sorted. So it was left to the developer to do the filtering that they wanted themselves.

Usually, they need the closest raycast intersection that has a particular tag or some other condition. To do this would cost O(n).

However, if we sorted it, it would cost O (n log n) which is more expensive

1 Like

I got it, but it is not about distance. For example ray hits red box first, than ground. But the ground pivot is closer than the red box. In summary, what I need is the order of hits. Do you have an idea for this?

Hi @mehmedcan! Is there no way to use the raycast hit to determine the order? (Something like `result[0].point`

instead of the position of the entity).

Hi @Albertos, as in the first photo of the topic, the `results[0]`

entity is random for RaycastAll, so unfortunately this value `results[0].point`

does not represent the first raycast hit poisition.

I understand the problem, but what I mean is to use the hit points to determine which hit is first. You need to do a loop for this.

What will be the comparison criteria in this loop? Result[] order and distance don’t work for this.

If you know which hit point is closer you can place the results in the right order I guess?

Got it, hitPoint distance comparison can help me to sort all objects, I will ll try that way. Thank you for help @Albertos

1 Like

You can create your own raycast function, and read the property called `m_closestHitFraction`

of the `Ammo.AllHitsRayResultCallback`

.

You can do the same thing that engine is doing, but additionally you can store the fraction value:

```
const rayCallback = new Ammo.AllHitsRayResultCallback(ammoRayStart, ammoRayEnd);
...
const fraction = rayCallback.m_closestHitFraction; // [0, 1] range
```

The fraction will be a normalized distance from the start of the ray (zero) till the end of the ray (one). So, if fraction, for example, equals 0.3, it means the contact happened at 30% of the ray’s length. You can then sort the contacts by fraction value, where lower value means the ray hit earlier.

You can check out sources about how the engine does the raycast:

1 Like