Cocos 2D Demo Side Scrolling

Mobile gaming represents an important opportunity for new levels of engagement. Here at HiDef we're especially interested in Serious Games, those that seek to educate or inspire while achieving a completely entertaining experience. Cocos2D is one of the most popular open-source 2D game engines for the iPhone/iPod touch, if not the only solution currently available. In this tutorial I will walk you through the process of creating a simple touch-based side scrolling demo. This tutorial assumes that you have:

  • The latest iPhone SDK already downloaded and installed.
  • Created your own map using your favorite editor (I use Tiled - http://mapeditor.org) in TMX file format.

Before we continue, download the engine from http://www.cocos2d-iphone.org/download, grab the latest archive, and save it. At the time of this writing version 0.8.2 is the latest.

Using your favorite archiving tool, extract the contents of the archive you just downloaded, then open a console shell and change directory cd to where you extracted your files. Cocos2D already comes with a useful template that can be used to quickly start a new project in XCode. To install the template run the following command at the console:

	
./install_template.sh
	

Start XCode, select "File->New Project", and you should spot something similar:

Cocos2D Choose Template

Select "cocos2d-0.8.2 Application

Select "cocos2d-0.8.2 Application" and give your project a name.

You will end up with a project that contains the usual "Hello World" sample already coded for you. Go ahead, give it a try by selecting "Build and Go":

Cocos2D Build and Go

Select "Build and Go"

If the compiler complains of a missing SDK, you'll need to select an active SDK for your project:

Cocos2D Select active SDK

Select an active SDK

Choose the latest iPhone simulator. At the time of this writing 3.1.2 is the latest. Now try building your project once again. You should see the familiar "Hello World" text on the screen of your iPhone simulator:

Cocos2D Hello World

"Hello World" iPhone simulation

Create a new class by right-clicking "Classes" and selecting "Add->New File". Make sure "Objective-C class" is selected, then click "Next". Type in TileDemo for the name of your class and make sure "Also create TileDemo.h" is selected. This class will contain the code that will load and scroll your tile map.

Next you'll add the file tilemap.tmx to both your "Resources" and your tilemap graphic. Complete this step by right-clicking "Resources" and selecting "Add->Existing Files". Make sure "Copy items …" is selected, as it will help keep your project files organized.

Add the following code to your "TileDemo.h" file, replacing whatever is there already:

	
#import "cocos2d.h"
 
@interface TileDemo: Layer
{
     
}
 
+(id) scene;
 
@end 
	

Add the following code to your "TileDemo.m" file, once again replacing whatever is there already:

	
// cocos import
#import "cocos2d.h"
 
// local import
#import "TileDemo.h"
 
enum
{
      kTagTileMap = 1,
};
 
#pragma mark -
#pragma mark TileDemo
 
@implementation TileDemo
 
+(id) scene
{
      // 'scene' is an autorelease object.
      Scene* scene = [Scene node];
     
      // 'layer' is an autorelease object.
      TileDemo* layer = [TileDemo node];
     
      // add layer as a child to scene
      [scene addChild: layer];
     
      // return the scene
      return scene;
}
 
-(id) init
{
      if ((self = [super init]))
      {
           
            self.isTouchEnabled = YES;
           
            TMXTiledMap* map = [TMXTiledMap tiledMapWithTMXFile:@"tilemap.tmx"];
            [self addChild:map z:0 tag:kTagTileMap];
           
            CGSize s = map.contentSize;
            NSLog(@"ContentSize: %f, %f", s.width,s.height);
           
            for (AtlasSpriteManager* child in [map children])
            {
                  [[child texture] setAntiAliasTexParameters];
            }
      }
     
      return self;
}
 
-(void) dealloc
{
      [super dealloc];
}
 
-(void) registerWithTouchDispatcher
{
      [[TouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}
 
-(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event
{
      return YES;
}
 
-(void) ccTouchEnded:(UITouch*)touch withEvent:(UIEvent*)event
{
     
}
 
-(void) ccTouchCancelled:(UITouch*)touch withEvent:(UIEvent*)event
{
}
 
-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent*)event
{
      CGPoint touchLocation = [touch locationInView: [touch view]];    
      CGPoint prevLocation = [touch previousLocationInView: [touch view]];
     
      touchLocation = [[Director sharedDirector] convertToGL: touchLocation];
      prevLocation = [[Director sharedDirector] convertToGL: prevLocation];
      prevLocation.y = touchLocation.y;
     
      CGPoint diff = ccpSub(touchLocation,prevLocation);
     
      CocosNode* node = [self getChildByTag:kTagTileMap];
      CGPoint currentPos = [node position];
      [node setPosition: ccpAdd(currentPos, diff)];
}
 
@end
 
	

Now go ahead and run the project. You'll notice that "Hello World" is still there because you haven’t instructed the main application delegate class to use your new scene.

Do issue these instructions open ProjectNameAppDelegate.m and do the following:

  • Add #import "TileDemo.h" to the header section.
  • Add [[Director sharedDirector] setProjection:CCDirectorProjection2D]; just before runWithScene method in applicationDidFinishLaunching method. This makes sure our projections are all two dimensional, otherwise random artifacts will show up in your scene.
  • Modify [HelloWorld scene] to [TileDemo scene].

Run your project. You should see your tile map and be able to touch scroll your scene.

That's it! You have created your very own side scrolling demo. Now feel free to experiment with larger map sizes. In the next post I'll show you how to add tiled animations to your scene.