Today I started to do some basic AI using ray casts to gather information about nearby objects. Unfortunately there were some tricky hang ups that made this take a bit longer than expected, but now that I’ve figured them out I’m confident I could so something similar in a fraction of the time.
To save yourself some time if you’re planning on using ray casting in a Unity 2D game, go ahead and open up the project settings, and under Physics 2D and see if you have “Queries Start In Colliders” checked. Depending on your use case, you absolutely do, or absolutely do not want to check this box.
There are also some pretty fancy things you can do with layers, allowing you to exclude certain classifications of objects from specific ray casts, so that you could for example, do one sweep to check for enemies regardless of obstacles, and another to scan static collision objects. Of course, after only a few hours of messing around with ray casts, I don’t consider myself an expert. There are a lot of overrides that allow you to do pretty much anything you could want.
One last brief note, Unity helpfully provides Debug.DrawRay to visualize your ray casts. Although I would have found it more helpful to simply have an optional parameter for debug visualization, this works almost as well, and allows you to set your debug draw to pretty much exactly match your actual ray cast, allowing you to see where you’re messing up, which is easy to do when it comes to drawing lines in space, even in 2D.