Welcome to my Programming Blog...

I am currently working on a couple of projects: An original game called "Implosion" which I am porting from Flash to the iPad, and a remake of Q*bert in Python (pygame), as part of the class I am teaching. Please feel free to use the "Labels" (at right) to follow a specific project or theme. If you are one of my Python students, I recommend that you check out the Python thread.

Wednesday, January 12, 2011

Making a cocos2d tilemap, part 2

Continued from part 1
Continuing with a "cheat sheet" on how to add Tiles to your cocos2d project...
Again, this is largely from the work of the cocos2d official tutorial, Steffen Itterheim and Ray Wenderlich.

  1. In XCode, add your .png tileset and your .tmx file (from Tiled) to the resources section of your project.
  2. In the header file for your primary scene class, (e.g., HelloWorldScene.h) create a variable to hold your map:
    CCTMXTiledMap* theMap;
  3. Then switch over to your .m file and add a line to the init function to load and initialize the tilemap:
    theMap = [CCTMXTiledMap tiledMapWithTMXFile:@"yourfile.tmx"];
  4. You can make the tilemap appear onscreen by adding it as a child to another layer:
    [self addChild: theMap];
  5. If you wish to make the background move around and keep another object stationary one easy way is to move the scene itself one way every time you move the object in which it resides the other. (For example, if the objects' x-position gets bigger by 5 pixels, then move the scene to the left by 5 pixels to compensate.) Alternately, you can just tell the scene to recenter on the screen during the update: cycle - we wrote a nice function called "centerScreenOnPenguin," which you could modify. (Here's a shorter version of the one we wrote together.)
    (void)centerWindowOnPenguin
    {
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
        gameLayer.position = ccp(screenSize.width/2-[thePenguin getPosition].x,
                                 screenSize.height/2-[thePenguin getPosition].y);
    }
  6. To give the penguin a starting location, we get a point that is based on the information in the "objects" layer. In the HelloWorld init function, we added in some code after we loaded the map but before we created the penguin. (Again, here is a more compact version.)
    NSMutableDictionary* spawnPointRecord = [[theMap objectGroupNamed:@"objects"] objectNamed:@"playerStart"];
    CGPoint startPos = ccp([[spawnPointRecord valueForKey:@"x"] intValue],
                           [[spawnPointRecord valueForKey:@"y"] intValue]);
    Note: the "objects" and "playerStart" need to match what you picked when you set up your Tiled file.
Coming up - handling collisions with walls in your tiled world.

No comments:

Post a Comment