# Boids: Physics collision check in Compute Shader?

Hey!

I have a flocking simulation that is supposed to stay inside a custom shape that I define with a PolygonCollider2D. So for every “boid” I check every frame if it is indeed still inside the collider. Let’s just say, the framerate is dropping significantly with the amount of boids I will need for my project.

Would it be possible to have a Compute Shader do these Physics checks? I still have to read into Compute Shaders, but before that, I would like to know if my plan even makes sense.

Of course I appreciate any other ideas on how to keep my boids inside a custom shape that is more performance friendly

Thank you!

It doesn’t really make sense if I’m honest; sounds like a square peg in a round hole. If you have a custom (potentially concave) shape for a point in space to stay inside then you’d be best doing this yourself. Also, you’re saying “shape” but it sounds like you do mean an arbitrary boundary.

Assuming the boundary doesn’t change, you’d be passing in a simple structure to the compute shader to use to check, maybe an array of edges/AABB or something but this depends on the algorithm you’d use which itself depends on if the boundary is static, convex etc.

A point in a convex boundary is an easy test (you can find algorithms online easily). For concave it’s more tricky but in the end you’d likely to be doing a point/circle vs boundary check. Of course, you’d need to set-up a constraint too to ensure you move back within the boundary but again, if you can identify the closest edge you’re closest to and on the wrong side of then it’s an easy thing to project your position back into or on the other side of that edge.

1 Like

Thank you very much for the fast reply! Yes I mean arbitrary boundary, like simplified borders on a map So I guess I will look for fast algorithms to do the checks. At the moment I’m using Physics2D.OverlapPoint, but maybe that is too slow for 500+ boids…

It depends I guess but it’s not really the best use of the techology. Even a simple check for 500 points against an arbitrary boundary using a job would make it much quicker, no need to use a compute shader and you’d be able to automatically use all the CPU cores on the device.

Because you’re using a PolygonCollider2D then you’d need to ensure that those boids don’t interact with it if you’re only using a query i.e. turn off their respective layers. That said, I’d say a simpler dedicated check would be best.

1 Like

Thanks again! I was just looking at the job system, hoping that it could be helpful in this case

1 Like