Thanks to Back to Work (or was it The Incomparable, or was it Accidental Tech Podcast?) I am enjoying a week trial of Lynda.com. So I decide to slam a Unity tutorial into my brain because, hey, let’s learn game programming.
Ran into an issue in lesson 5-4.
Unity uses OnTriggerEnter2D and OnTriggerExit2D to handle collisions for things such as item pickups, zones or whatever. Two things enter each other and something triggers. Shocking.
Problem was the tutorial had some weird logic. It would check if the player entered an enemy’s area and then start its attack animation. Instead of making the enemy deadly once the animation starts, it sets the enemy as attacking a few frames into the animation. This is a cool trick that is so easy to do in Unity that I almost am starting to like it a little. Thing is, this logic was also checking if the enemy was attacking.
Which doesn’t exactly work, right? The Enter trigger already happened. The player would have to enter, leave and re-enter before the animation finished, and why would they?
Turns out that there is an OnTriggerStay2D which is exactly where I want to check things. Boom. Player explodes.
Except what I don’t get is why it worked in the tutorial. Either something changed since the tutorial came out (Although that doesn’t make sense to begin with.) or I am doing something wrong. However as the provided sample code also fails to work properly, and the logic just makes more sense this way, I’ll pretend I am awesome and figured out an issue.