How expensive is Physics2D.Raycast?

Long story short, I’m working on a 2D game that’s not super complex, but I’m using Physics2D.Raycast in the FixedUpdate() method for a handful of objects.

The reason I’m using it is to get objects in the game world relative to my player (i.e. get the tile above or below you). Should I be concerned for performance or am I worried about nothing?

Thanks!
Ed

My quick answer is that you’re probably fine unless you’re doing a ton of raycasts each frame. How many is “too much” depends on your hardware (pc vs mobile, new pc vs old pc, etc.)

Raycasts aren’t too expensive to do each frame, and FixedUpdate isn’t even every frame. It mostly depends on how many objects you’re raycasting from and against… If you know the number of raycasters will remain relatively small then it won’t be too expensive (it’s hard to give a number for how many is “too much”, but basically don’t create a scenario where a ton of raycasters get generated).

You can make a raycast cheaper by using a layer mask to only test object you actually want the ray to hit. This doesn’t have a huge impact on 1 raycast, but the optimizations add up if you’re doing a lot of raycasts.

1 Like

Cool thanks, I guess I’ll focus my attention elsewhere.