Successively finds part on the same ray, passing each to callback (closest first), until the callback returns true, or until there are no more parts on the ray.
workspace:FindSuccessivePartsOnRay(ray, function(part,position,material,normal)
if partIsWhatImLookingFor(part) then
--do stuff
return true
end
end)
This is a generic replacement for all the ignoreParts/ignoreTerrain/whatever parameters one might desire, plus its of course more flexible in that you can find multiple parts (like if you really do want all the parts ON the ray, not the first one, or if you want some bullet to go through N targets)
Currently I have to use my own so I can have smart logics to decide what set of parts I care about, without figuring out how to construct the complement of that set, as is required by the current query methods.
Not a problem for FindPartsInRegion as its trivial to filter the parts afterwards, though it might make sense for that too.
While the filter callback is an interesting idea, it doesn’t really work out because it’s kind of slow to invoke Lua from C++, especially repeatedly. It would be better to return an array. Even returning everything would be better than invoking Lua so much!
I suggested something like this a while back: Raycasting with Callback
I ended up implementing it myself in lua; add stuff to the ignore list as you go.
Do note that in practise the callback would only be invoked maybe 1-3 times for most practical uses.
Of course, if a sorted table is still faster to return (including normal,position,material for each of the parts!) and iterate on Lua side (to find the part you need), then sure.
Is it possible to make it internally retrieve a sorted table of all parts on ray, then on Lua side implement the callback thing? This would leave room for later optimizations, at least (you cant really go back once you give the user a full table as part of the API)
As in it being “sorted”, if the parts internally get added in the order they get hit, it’ll be already sorted.
Another addition would probably be a parameter ‘amount’ for the max amount of parts to be hit. (Not that it’s needed, but some people might want to use it, and prevent it from hitting thousands of parts) (No idea where to put the argument. As first parameter, so new parameters to FindPartOnRay are in order?)
There are still some issues with invoking Lua in random places. What if you move stuff during the callback? It might have some crazy consequences for the physics engine.