Monthly Archives: December 2013

Cocos2D-XNA Tutorial 3: Collision Detection

Well, I’m starting to settle into this Cocos2d-XNA framework and I must say, I’m really having a great time with it.  The last few weeks have been spent exploring collision detection techniques and how I might implement pixel-perfect collisions in C2D, so I thought I’d share my wanderings with you in this post.  It seemed like a natural progression to me following my first couple areas of exploration which concerned using sprites and actions in the framework, learning the basics of movement, rotation, scaling, etc.  With collision detection implemented, I have the basic tools that are necessary to create a variety of different games; a lot of the other stuff revolves around making a game shiny, adding game play depth, etc.

Collision detection in games is an interesting subject, comprised of numerous and varied algorithms based on the particular issues your game is trying to solve.  In general, you won’t find one collision detection method that you’ll use in all the games you ever write.  For example, one game may only require a simple bounding box collision to function well as being in the general area is good enough (think character collisions for starting an encounter in an RPG game).  However, that won’t fly for a shooting style game where your guy disappears off the screen before it looks like the bullet gets there (think crappy game engine) – I mean, that bullet missed my guy by a full two pixels!  Boo.  So you need to pick a method that fits the needs of your game and doesn’t detract from the game play.  In many instances, a layered approach using a few different algorithms may yield the best results depending on the game.

One of the main goals of good collision detection is the speed at which your game can detect a collision.  A lot of times, you’ll be checking for collisions during each update cycle of your game and slow, lumbering collision detection can mean dropped frame rates and less time to do other needed things in your game.  For the example I chose for this tutorial (a space shooter – I’ve always loved games like Galaga, etc.), I needed a reasonably fast algorithm to check for pixel-perfect collisions between my ship, enemy ships, and bullets.  Even with 2013 technology, doing a straightforward pixel level check between most objects (or even just a few objects) in a game is extremely slow and wasteful as well, since many objects probably don’t even need to be checked if they aren’t near each other, don’t collide with each other, etc.

C2D provides the CCMaskedSprite object to help facilitate pixel-perfect collisions in your games.  Derived from the CCSprite object, It accepts a byte array containing the mask of the sprite for the object, which is just a text file of 0/1 values stored in a *.mask file, with 0 representing transparent areas of the sprite where a collision shouldn’t occur.  You check for a collision using the CollidesWith method of the class.  It does a simple bounding box collision check first and if that succeeds, it performs checking against the masks of the sprites for a true collision.  It also returns the point at which the collision occurred if you need it.

It wasn’t obvious how these masks were created, but a post on the forum helped clear that up.  Masks for your sprites can be created with the Collision Mask Generator utility in the Cocos2d-XNA framework, found in the cocos2d-xna/tools/CollisionMaskGenerator directory.  After generating your mask files, you’ll need a way store them in your game.  One of the chaps from the C2D dev team (totallyevil) suggests storing them as embedded resources in your assembly instead of XNB files from your Content project as they’re easier to port to other platforms and you avoid custom content issues.

Even with the help that C2D provides with the CCMaskedSprite, I still needed a way to narrow down my collisions so I wasn’t checking all sprites in my game for collisions during each update cycle.  So after some Google-Fu and some meandering about the Internets, I found a good article on 2D collision detection methods that I think is well worth reading called Methodologies for Quick Approximation of 2D Collision Detection Using Polygon Armatures.  One of the suggestions it provided was to only check objects for collision that are near each other on the screen, which makes good sense in my scenario (and probably in general) as most times I won’t have a bunch of objects together in the same place.  You can do this by implementing a spatial partitioning system, which is just a fancy way to describe splitting the screen up into a defined set of spaces.  A tree structure is often used for such a system, but the authors suggested a simpler approach of a predefined partition size that only requires each object to sorted into it’s appropriate location (they refer to this as ‘binning’).  I refer to it as a Collision Grid.  One assumption made with this particular method is that the objects in the game are of similar size; in other words, the size of each square in the grid can contain any whole object in your game.  This means that any object would only be in 1, 2, or 4 grid squares in a given update cycle, based on whether it crossed horizontal/vertical boundaries of a grid square.  If objects aren’t of a similar size, modifications would have to be made or a different scheme used altogether.

I basically implemented my collision grid as follows:

  • I start with my collision grid at a fixed size of 100 x 100 pixels per grid square.  I then distribute any space remaining across all grid squares to “fit” the screen as much as possible.  This provides you with a set of defined rows/columns for the screen.  For example, at a resolution of 1024 x 768, I have 8 rows x 11 columns to contain all visible space on the screen.
  • I number each square in my collision grid starting from 0 at the bottom left of the screen, continuing to the right across columns and then up by rows.  For example, a grid with 8 rows and 11 columns would be numbered 0-10 for row 1, 11-20 for row 2, etc.
  • I created a Dictionary of ‘bins’ (i.e. grid squares), with each bin containing a List of the game objects that it contains for that update cycle (Dictionary<int,List<GameObject>>).
  • During each update cycle, the following steps are taken:
    • The dictionary of bins is cleared.
    • Each game object is assigned to the appropriate bin based on the screen position of the four corners of it’s bounding box.
    • I check the player’s ship and player’s missiles for possible collisions by seeing if their bins contain any other objects (checking enemy and enemy missile collisions would be redundant in my case).
    • After sorting out any invalid collisions (e.g. player ship with player bullet, etc.), I then call the CCMaskedSprite.CollidesWith method from C2D to check for an actual collision.
    • Rinse and repeat.

Aside from the collision grid, I also made a base class called GameObject from which all the various game objects derive (Ship, Enemy, Bullet).  This allowed me to keep most code with the appropriate objects, though the processing is mainly handled in the GameObjectLayer class since it knows about all the players and the collision grid.  You can see a screenshot of the final result below.

CollisionDetection

As I meant this to be a learning exercise as opposed to a real game, I built in some controls to the game to show various parts and let you control some objects so you can get a feel for how the collision works and/or if you wanted to break through the code easily.  The controls are as follows:

  • Arrow keys – move the player’s ship up/down/left/right.  Speed of the ship is adjustable through the ShipSpeed constant in the Ship class, in case you want to slow it down for testing.
  • Left Control – Fires bullet from player’s ship.
  • B – Show/hide bounding boxes for the game objects on the screen.
  • G – Show/hide the collision grid on the screen.
  • E – Enables/disables movement of enemy ships.
  • S – Enables/disables movement of enemy bullets.

The result of this effort is contained in a new project called Collision Detection in my Cocos2D-XNA-Tutorials solution on GitHub.  The code is heavily commented so you should be able to find your way around without too much effort.  Hopefully you find it helpful, I had a lot of fun coding it and seeing it work.  Well, that’s it for now, it’s past my bed time.  Happy proggy.

Cocos2D-XNA Tutorial 2: Basic Actions

In my last post (Cocos2D-XNA Tutorial 1: Basic Sprites), I explored some of the basic ways that sprites in Cocos2D-XNA (C2D from here on) could be used in a game.  In that project, I changed properties on the sprite object directly to perform different actions, such as movement, scaling, rotation, etc.  In some cases, this is appropriate so that you can control the sprites exactly the way you want.  But sometimes it would be nice to have a sprite do something specific repeatedly or in a specific sequence of actions, without having to write a bunch of boilerplate code to make it work.

Well then, welcome to Actions in C2D.  Actions provide a great way to manipulate the sprites in a game by performing changes to one or more properties of the sprite.  C2D provides a large number of actions that can be used in your game and I debated whether to include them all in this post… since I’m still learning, I don’t have a perfect understanding of how they all work as I haven’t used them all yet. :)  However, I haven’t been able to find a lot of good references on the internet that provide a decent description of how they work (though most are reasonably obvious), so I thought I’d do my best to list them all here for reference.  If you notice something amiss here, any actions that I’ve missed, or suggestions for improvement, drop me a comment.

With that said, there are two basic types of actions:

  • Instant – The action is performed immediately on the sprite.  The following list shows the instant actions available in C2D:
    • CCFlipX – Flips the sprite on the horizontal axis.
    • CCFlipY – Flips the sprite on the vertical axis.
    • CCHide – Makes the sprite invisible on the screen.
    • CCPlace – Moves the sprite to the specified position.
    • CCRemoveSelf – Removes the sprite from it’s associated parent.
    • CCReuseGrid – Allows a grid to be reused a specified number of times (not sure how this is used??)
    • CCShow – Makes the sprite visible on the screen.
    • CCStopGrid – Stops an effect being executed on a sprite.
    • CCToggleVisibility – Toggles the visible state of the sprite.
  • Interval – The action is performed over a period of time on the sprite.  Also, almost all interval actions have a Reverse method that lets you reverse the action.  The following list shows the interval actions available in C2D:
    • CCAnimate – Animates a sprite using the associated sprite frames.
    • CCBezierBy – Moves a sprite in a bezier curve relative to the sprite’s current position.
    • CCBezierTo – Moves a sprite in a bezier curve at a fixed starting and ending position on the screen.
    • CCBlink – Toggles the visibility of a sprite off and on to flash it a specified number of times on the screen.
    • CCCardinalSplineBy – Moves a sprite in a curved motion based on a specified tension and series of control points relative to the sprite’s current position.  Microsoft has a decent description of Cardinal Splines, though their tension values are backwards vs. C2D (in C2D, 0 = smooth curve, 1 = straight line).
    • CCCardinalSplineTo – Moves a sprite in a curved motion based on a specified tension and series of fixed control points on the screen.
    • CCCatmullRomBy – Moves a sprite in a curved motion based on a series of control points relative to the sprite’s current position.  This page provides some introductory information about Catmull-Rom splines.
    • CCCatmullRomTo – Moves a sprite in a curved motion based on a series of fixed control points on the screen.
    • CCDelayTime – Waits a specified amount of time before continuing a sprite’s next action.  Useful in action sequences.
    • CCFadeIn – Adjusts the opacity of a sprite until it is completely visible on the screen.
    • CCFadeOut – Adjusts the opacity of a sprite until it is completely invisible on the screen.
    • CCFadeTo – Adjusts the opacity of a sprite to a specified level.
    • CCJumpBy – Makes a sprite jump on the screen by a specified amount, amplitude, and number of times relative to the sprite’s current position.
    • CCJumpTo – Makes a sprite jump on the screen to a specified position by a specified amount, amplitude, and number of times.
    • CCMoveBy – Moves a sprite by a specified amount on the screen relative to the sprite’s current position.
    • CCMoveTo – Moves a sprite to a specified position on the screen.
    • CCReverseTime -
    • CCRotateBy – Rotates a sprite by a specified number of degrees relative to the sprite’s current position.
    • CCRotateTo – Rotates a sprite a specified number of degrees on the screen.
    • CCScaleBy – Adjusts the size of a sprite by a specified amount relative to the sprite’s current size.  Values: 1 = original size, < 1 = smaller, > 1 = larger
    • CCScaleTo – Adjusts the size of a sprite to a specified amount.
    • CCSkewBy – Adjusts the horizontal and/or vertical angle of the sprite by a specified amount relative to the sprite’s current angle.
    • CCSkewTo – Adjusts the horizontal and/or vertical angle of the sprite to the specified amount.
    • CCTargetedAction – Applies an action to the specified target sprite.
    • CCTintBy – Adjusts the tint of a sprite by a specified RGB amount relative to the sprite’s current color.
    • CCTintTo – Adjusts the tint of a sprite to a specified RGB value.

C2D also provides a special set of composite interval actions called Easing actions, which modify the speed of the specified action while not altering the total running time (e.g. if an action should run in 2 seconds, it will continue to run in 2 seconds but it’s acceleration will be altered).  These actions come in three flavors:

  • In – The acceleration happens at the beginning of the action.
  • Out – The acceleration happens at the end of the action.
  • InOut – The acceleration happens at the beginning and end of the action.

These easing actions can be applied to movement, rotation, skewing, etc.  C2D provides the following easing actions:

  • CCEaseBackIn – Moves a sprite slightly backwards at the beginning of the action.
  • CCEaseBackInOut – Moves a sprite slightly backwards at the beginning and end of the action.
  • CCEaseBackOut – Moves a sprite slightly backwards at the end of the action.
  • CCEaseBounceIn – Moves a sprite with a bouncing motion at the beginning of the action.
  • CCEaseBounceInOut – Moves a sprite with a bouncing motion at the beginning and end of the action.
  • CCEaseBounceOut – Moves a sprite with a bouncing motion at the end of the action.
  • CCEaseCustom – Moves a sprite using a custom function.
  • CCEaseElasticIn – Moves a sprite in an elastic motion at the beginning of the action.
  • CCEaseElasticInOut – Moves a sprite in an elastic motion at the beginning and end of the action.
  • CCEaseElasticOut – Moves a sprite in an elastic motion at the end of the action.
  • CCEaseExponentialIn – Moves a sprite slowly at the beginning of the action, then with increasing speed.
  • CCEaseExponentialInOut – Moves a sprite slowly at the beginning and end of the action, with increasing speed in the middle.
  • CCEaseExponentialOut – Moves a sprite slowly at the end of the action, with increased speed at the beginning.
  • CCEaseIn – Moves a sprite slowly over a specified duration at the beginning of the action.
  • CCEaseInOut – Moves a sprite slowly over a specified duration at the beginning and end of the action.
  • CCEaseOut – Moves a sprite slowly over a specified duration at the end of the action.
  • CCEaseSineIn – Moves a sprite in a yo-yo motion, moving from beginning to end position and then back to beginning position.
  • CCEaseSineInOut – Moves a sprite slowly from beginning to end of the action.
  • CCEaseSineOut – Moves a sprite to the ending position, reverses to move beyond the beginning position by the same distance, then ends at the beginning position.

Using the basic actions in C2D can help simplify the coding in your game a good bit.  But where actions really shine in C2D is the ability to execute groups of actions in various ways, allowing you to do some wicked cool stuff.  The following special actions exist for this purpose:

  • CCParallel – Executes several actions at the same time.  Appears identical to CCSpawn below, which is the standard cocos2d method of running actions in parallel.  From what I can tell, this class appears to be exclusive to Cocos2d-XNA.
  • CCRepeat – Repeats an action a specified number of times.
  • CCRepeatForever – Repeats the action indefinitely.
  • CCSequence – Executes a series of actions one after another.
  • CCSpawn – Executes several actions at the same time.

Using the above actions, you can accomplish quite a number of things in your game with ease and simplicity that would otherwise take you some considerable time to implement yourself.  Also, if you’d like to write your own custom actions, then you can inherit from the appropriate base class and code away, so the possibilities are nearly endless.  The original cocos2d Programming Guide has a section about creating custom actions, which you should be able to translate over to C2D without too much difficulty.

I created a new project called Basic Actions in my Cocos2d-XNA-Tutorials solution on GitHub that explores some of the actions listed above.  It should be enough to give you a good idea on how to use actions and explore the ones I didn’t implement in the project.

Well, that’s about it for this post… it took several iterations to get through as I couldn’t get it all churned out in one sitting.  Hopefully you find it helpful.  Happy proggy.