Saturday, May 10, 2014

Unity3D Native 2D - A little about collision detection

As I mentioned before, all of my game objects actually use the 3D version of the colliders/rigidbodies.  This is because Unity currently lacks the features in its 2D API to support different force modes.  Now that I've mentioned all of the core game objects necessary for the game, let's look at how collision detection can finish the core game loop.  There are two conditions for the game over state; The player can hit the columns or the player can hit the floor.  The character is expected to behave differently when we collide with these objects. I fthe player hits the columns, then I expect the player to fall down to floor before the game over screen appears.  If the player hits the floor, I expect the player to immediately go to the game over screen.  To deal with these two conditions, I declare two new layers in the Unity project as shown below.


In code, I can reference these layers by their index values.  In Unity, when a trigger collider hits another collider, we can listen for this event using several API functions.  The one I will be using is OnTriggerEnter.  Let's take a look at the code that is needed for handling death.


The alive variable allows us to control whether we should listen to player input.  By wrapping the input code with an if statement that checks if the player is alive, I can stop the player from jumping once the bird hits something.  Notice in the Death method, we send out an event call and this is because other systems such as the ColumnScroll script needs to stop their scrolling when the player dies.  So in the ColumnScroll, we do something like the following.



This wraps up most of the core functionality I used in Unity and its Unity2D API to create a FlappyBird clone. If you have a question or feedback, feel free to leave a comment below!

No comments:

Post a Comment