Click to Play!

Thursday, December 12, 2013

TriGrid Collision

     Getting triangles to crash into each other was a bit trickier than I thought. I tried polygon collision boxes, turn-based movement, raycasts, and vision cones. In the end, simple boxes worked best but there was still the problem of objects colliding while facing certain directions. Here's how I used Unity's 2D Toolkit plugin to make sprites collide in my first Unity game: TriGrid.

      The 2D Toolkit comes with a neat little feature that quickly became my favorite. A fully customizable collision box maker. Back when I used Cocos2d to do this, I faces delicate situations where I had to carefully code every possible collision between two rectangles. Now it's a matter of playing with polygon edges in a menu or choosing a preset from a drop-down menu.

      The enemies are pretty small and 20x20 boxes make up every object relevant to gameplay (within the grid). I made the collision boxes slightly smaller than 20x20 to be a bit more forgiving to players who just barely touch an enemy. I had to be careful with making it too small because the moving objects shouldn't be allowed to clip through walls.

      I even wrote scripts to help objects avoid clipping walls. It was separated from the code for colliding with other objects to keep things organized. I also did it because I wanted objects to be able to overlap each other, but freeze when colliding with a wall.

     This piece of code is attached to an enemy object so it can detect where the pink border around the map is. I also set up variables that control how far ahead the object checks for a collision on each size.

      This is the code that checks to see if the next movement square is occupied or not. To do this I have a raycast, a sort of invisible arm reaching out to feel for walls. I attached this to enemies and the player object. If the space the object was moving to is blocked, the object doesn't move there. Some enemies use this to see where they could make a turn in order to keep moving.

     This is the code for determining what to do when objects collide. The player object is a trigger and when its collision box touches an enemy's this code calculates which direction both objects are facing to determine which object gets destroyed. The player has to hit the enemy from behind, otherwise the player explodes and the enemies reset.

      This function happens when an object that collided with an enemy, stops colliding with it. In this method the destroyed object either respawns or is removed from gameplay.

      It's all basic stuff really. But that's because Unity is just a better tool for me to make things with. This stuff used to be a confusing nightmare but is now made simple, leaving less room for error. I think the world is better off with less software bugs anyway.

No comments:

Post a Comment