How does RigidBody2D.cast know which at what order to save the array?

If I have multiple game objects in a row (with boxCollider2D and a RigidBody2D), and a gameObject that shoots a RigidBody2D.cast (and saves it to an array rather then a single RayCastHit2D[ ]) then the order of the array will be from the closest to the furthest. But, what if I have something like this:
9879546--1425051--upload_2024-6-8_12-55-29.png
Note: the green gameObject shoots the rb.cast, and it is shooting it to the right and the 2 white gameObjects have the same x value.
The cast will hit both of them at the same time, so witch gameObject is going to be stored first? the bottom one? the upper one? or is it random?

In general, I don't think Rigidbody2D.Cast guarantees any sort of ordering in the results. Nothing like this is mentioned in the documentation.
https://docs.unity3d.com/ScriptReference/Rigidbody2D.Cast.html


All 2D physics cast operations sort implicitly by the distance results (unlike 3D physics).


It uses a simple sort function so if they're both in the results at the same distance then which one is first will be the first one returned from the internal broadphase which is effectively undefined. If you need specific post-sort order then simply run a sort function over it.

2 Likes


Thanks

1 Like