Stopping a raycast on first object hit?

I’m currently raycasting on mouseMove, an array of objects in the scene and I realistically only need the very first object that is hit, nothing else after that. It seems wasteful to continue the cast & search despite my result already being satisfied. Is there a built-in way of doing this, if not, would it be easy to hack in?
Or would the performance improvement be minuscule?


I assume you are using Raycaster.intersectObjects(), right? The method tests the entire given array of 3D objects and sorts the intersections per distance since in many use cases you want the closest intersection point (and not just an arbitrary one). If you do not need this logic in your app, I suggest you use Raycaster.intersectObject() instead and raycast against each object individually. You can then abort the intersection test as soon as you have an intersection point.

1 Like

Not sure why I didn’t think of that, seeing as Raycaster.intersectObjects does that internally anyway, I believe, just sorts the end result by distance. Thanks!

I didn’t know about the singular intersectObject() until I read this thread. That is awesome :slight_smile:

1 Like

That’s why it’s good to read the documentation… time to time :beers:

I am coming from OpenSim, docs are a new concept that I am getting used to. :wink:

1 Like