Book Image

Creating Games with cocos2d for iPhone 2

By : Paul Nygard
Book Image

Creating Games with cocos2d for iPhone 2

By: Paul Nygard

Overview of this book

Cocos2d for iPhone is a simple (but powerful) 2D framework that makes it easy to create games for the iPhone. There are thousands of games in the App Store already using cocos2d. Game development has never been this approachable and easy to get started. "Creating Games with cocos2d for iPhone 2" takes you through the entire process of designing and building nine complete games for the iPhone, iPod Touch, or iPad using cocos2d 2.0. The projects start simply and gradually increase in complexity, building on the lessons learned in previous chapters. Good design practices are emphasized throughout. From a simple match game to an endless runner, you will learn how to build a wide variety of game styles. You will learn how to implement animation, actions, create "artificial randomness", use the Box2D physics engine, create tile maps, and even use Bluetooth to play between two devices. "Creating games with cocos2d for iPhone 2" will take your game building skills to the next level.
Table of Contents (16 chapters)
Creating Games with cocos2d for iPhone 2
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Tile helper methods


One of the challenges in using tile maps is that we have at least two different coordinate positions that can be used to refer to a position on the map: pixels on the tilemap, and the tile coordinates. The tile coordinates relate to each individual tile, so the top left tile is (0,0) and the bottom right is (49,49) for our 50 by 50 map. What we need are some helper methods to easily convert between the two.

Filename: TDPlayfieldLayer.m

-(CGPoint)tileCoordForPos:(CGPoint)pos {
    // Convert map posiiton to tile coordinate
    NSInteger x = pos.x / tw;
    NSInteger y = ((tmh * th) - pos.y) / th;
    
    return ccp(x,y);
}

Here we are finally making use of the shorthand variables we saw in the init method. As a refresher, the variables are as follows:

  • tmw = tilemap width

  • tmh = tilemap height

  • tw = tile width

  • th = tile height

So the x value is the position divided by the tile width. For the y value, the calculation is a little longer, because the origin point of the tile...