Archive for the 'cocos2d' Category

Page 3 of 5

cocos Live: a high score server for cocos2d

Cocos Live is a service that tries to help iPhone Indie Game Developers by giving them an API to solve their online requirements.

As of version 0.1, the only feature available is the High Score Server. Future versions will have more features.

To use the High Score Server you need to:

  1. Have a valid Google account
  2. Sign in into Cocos Live with that account
  3. Create a game, customize it, and copy the secret key

Requesting a score

-(void) requestScore
{
    // create a Request object for the game "DemoGame" 
    // You need to implement the Score Request Delegate
    ScoreServerRequest *request = [[ScoreServerRequest alloc] initWithGameName:@"DemoGame" delegate:self];
 
     /* use kQueryFlagIgnore to request World scores */
     tQueryFlags flags = kQueryFlagIgnore;
 
     /* or use kQueryFlagCountry to request the best scores of your country */
     // tQueryFlags flags = kQueryFlagByCountry;
 
     // request the first 15 scores ( offset:0 limit:15)
     // request AllTime best scores (this is the only supported option in v0.1
     // request the scores for the category "easy"
     [request requestScores:kQueryAllTime limit:15 offset:0 flags:flags category:@"easy"];
 
     // Release. It won't be freed from memory until the connection fails or suceeds
     [request release];
 }
 
// ScoreRequest delegate
-(void) scoreRequestOk: (id) sender
{
// the scores are stored in a NSArrayNSArray *scores = [sender parseScores];
 
 // Display them as you wish: using a UITableView,
 // a custom CocosNode, etc...
 }
 
-(void) scoreRequestFail: (id) sender
{
// request failed. Display an error message.
}

Posting a score

-(void) postScore
{
    // Create que "post" object for the game "DemoGame"
    // The gameKey is the secret key that is generated when you create you game in cocos live.
    // This secret key is used to prevent spoofing the high
    scoresScoreServerPost *server = [[ScoreServerPost alloc] initWithGameName:@"DemoGame" gameKey:@"e8e0765de336f46b17a39ad652ee4d39" delegate:self];
 
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:4];
 
    // usr_ are fields that can be modified.
    // set score[dict setObject: [NSNumber numberWithInt: 340 ] forKey:@"cc_score"];
    // set speed[dict setObject: [NSNumber numberWithInt: 120 ] forKey:@"usr_speed"];
    // set angle[dict setObject: [NSNumber numberWithInt: 92 ] forKey:@"usr_angle"];
    // set playername[dict setObject:@"Ricardo" forKey:@"usr_playername"];
    // set player type[dict setObject: [NSNumber numberWithInt: 0 ] forKey:@"usr_playertype"];
 
     // cc_ are fields that cannot be modified. cocos fields
     // set category... it can be "easy", "medium", whatever you want.
     [dict setObject:@"easy" forKey:@"cc_category"];
 
    [server sendScore:dict];
 
     // Release. It won't be freed from memory until the connection fails or suceeds
     [server release];
 }
 
// PostScore Delegate
-(void) scorePostOk: (id) sender
{
    // Score post successful
}
 
-(void) scorePostFail: (id) sender
{
    // score post failed
    tPostStatus status = [sender postStatus];
    if( status == kPostStatusPostFailed ) {
        // an error with the server ?
        // try again
    }else if( status == kPostStatusConnectionFailed ) {
        // a error establishing the connection ?
        // turn-on wifi, and then try again
    }
}

For further information download cocos2d for iPhone v0.7, try the cocosLiveDemo example and read the cocosLiveDemo.m file.

cocos2d number-one open source project for iPhone


According to The Register, cocos2d for iPhone, is the number-one opensource project for iPhone.

“Mobile saw 120 new open-source projects, with 40 targeting the iPhone. The number-one project was 2D famework cocos2d-iphone, followed by zipper image viewer iphone-comicviewer and iphone-com, for iPhone applications that use Win32 serial COM ports

Introduction to cocos2d’s effects

Special thanks to Ernesto Corvi and On-Core for porting all the Effects code from cocos2d-python to cocos2d-iphone.
THANK YOU!

Effects are a special kind of action. Instead of modifying normal properties like opacity, position, rotation, or scale, they modify a new kind of property: the grid property.

A grid property is like a matrix, it is a network of lines that cross each other to form a series of squares or rectangles.

These special actions render any CocosNode object (Layer, Scene, Sprite, etc.) into the grid, and you can transform the grid by moving its vertices.

There are 2 kind of grids: tiled grids and non-tiled grids. The difference is that the tiled grid is composed of individual tiles while the non-tiled grid is composed of vertices.

The following is an example of Ripple3D action, who uses a Grid3D (non-tiled) grid:

and the following is an example of FadeOutTR action, who uses a TiledGrid3D (tiled) grid:

How do I use them ?

Like any other action, it is executed by the do: selector. eg:

// Create an sprite
Sprite *grossini = [Sprite spriteWithFile:@"grossini.png"];

// Tell the sprite to execute the Liquid effect
[grossini do: [Liquid actionWithWaves:4 amplitude:20 grid:ccg(10,10) duration:5]];

Liquid, like any other grid action, receives the grid parameter. You can adjust the quality of the effect by increasing the size of the grid. But it also implies less FPS.

The Effects are IntervalAction actions so you can treat them like any other action. eg:

// create a Lens3D action
id lens = [Lens3D actionWithPosition:cpv(240,160) radius:240 grid:ccg(15,10) duration:8];

// create a Waved3D action
id waves = [Waves3D actionWithWaves:18 amplitude:80 grid:ccg(15,10) duration:10];

// create a sequence an repeat it forever
[grossini do: [RepeatForever actionWithAction: [Sequence actions: waves, lens, nil]]];

The following is the list of the available Grid3D (non-tiled) actions in v0.7:

Shaky3D Waves3D FlipX3D FlipY3D
Lens3D Liquid Waves Twirl
Ripple3D

The following is the list of the available TiledGrid3D (tiled) actions in v0.7:

ShakyTiles3D ShatteredTiles3D ShuffleTiles FadeOutTRTiles
FadeOutBLTiles FadeOutUpTiles FadeOutDownTiles TurnOffTiles
WavesTiles3D JumpTiles3D SplitRows SplitCols

Edit: fixed grammar errors, improved the layout

read-write TileMapAtlas (at last ;)

The TileMapAtlas object was introduced in cocos2d v0.5.0. Although it helped in creating big scenarios, a lot of functionality was missing, like the possibility to read and modify the atlas in runtime, isometric tiles, hex tiles, animations, etc.

From cocos2d v0.7 onwards, you can read/write the TileMapAtlas (the rest of the features will be included in v0.8)

So, how I do a read / write my TileMapAtlas in v0.7 ?

Let’s start by recalling how to create a TileMapAtlas. The API is same you were using since v0.5:


TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];
[self add:tilemap];

Since v0.7 you can read/write the TileMapAtlas but if you don’t want to, you might want to release the map from memory:

// Release the map from memory ONLY if won't read or write the tile map
[tilemap releaseMap];

But if you are going to read or write the map, DON’T release the memory. Otherwise, you won’t be able to read or modify the atlas.

To read the the value of a certain tile, or to iterate over all the tiles you can do the following:

// For example you can iterate over all the tiles
// using this code, but try to avoid the iteration
// over all your tiles in every frame. It's very expensive

for(int x=0; x < tilemap.tgaInfo->width; x++) {
for(int y=0; y < tilemap.tgaInfo->height; y++) {
ccRGBB c =[tilemap tileAt:ccg(x,y)];
if( c.r != 0 ) {
// only the channel 'r' (red) is used
// if r == 0 it means that it is transparent, it won't be rendered
}
}
}

And to modify a certain tile of the TileMapAtlas object you can do as follows:

int x = 20;
int y = 30;

// read value
ccRGBB c =[tilemap tileAt:ccg(x,y)];

// modify it
c.r = 21;

// and store it on the tile map atlas
[tilemap setTile:c at:ccg(x,y)];

Limitations: you can’t modify a position whose tile value is 0. If you know that you are going to modify a certain position of the atlas, don’t set the initial value with 0.

For more information see the AtlasDemo example: TestAtlas.m

AntiAliased / Aliased textures in cocos2d

From cocos2d v0.7 onwards it is easier to customize the texture’s parameters like GL_LINEAR, GL_NEAREST, CLAMP_TO_EDGE, etc.

By default all cocos2d’s textures are created with these values:

GL_TEXTURE_MIN_FILTER = GL_LINEAR;
GL_TEXTURE_MAG_FILTER = GL_LINEAR;
GL_TEXTURE_WRAP_S = GL_CLAMP_TO_EDGE;
GL_TEXTURE_WRAP_T = GL_CLAMP_TO_EDGE;

You can change the default parameters. eg:


// Change default texture's parameters
ccTexParams texParams;
texParams.minFilter = GL_NEAREST;
texParams.magFilter = GL_NEAREST;
texParams.wrapS = GL_REPEAT;
texParams.wrapT = GL_REPEAT;
[Texture2D setTexParameters: &texParams];

You can also change the texture’s parameters just for 1 texture. For example, if you want to create a TileMapAtlas with GL_NEAREST you should do this:

// save current state
[Texture2D saveTexParameters];

// set GL_NEAREST
ccTexParams texParams = [Texture2D texParameters];
texParams.minFilter = GL_NEAREST;
texParams.magFilter = GL_NEAREST;
[Texture2D setTexParameters: &texParams];

// create the texture
TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];

// restore state
[Texture2D restoreTexParameters];

or, you can use the helper function setAliasTexParameters:

// Save state
[Texture2D saveTexParameters];

// set Alias parameters
[Texture2D setAliasTexParameters];

// create the texture
TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];

// restore texture's parameters
[Texture2D restoreTexParameters];

For more information see the Texture2dDemo example file: Texture2dTest.m

PVRTC support in cocos2d


From cocos2d v0.7 onwards you can use non-raw PVRTC (PVR Texture compression) images. (Raw PVRTC images are supported since v0.5.2)

In order to load a non-raw PVRTC image you can use the same API that you were using to load PNG/BMP/JPEG images. eg:


// Sprite using PVRTC file
Sprite *img = [Sprite spriteWithFile:@"test_image.pvr"];

// Texture Atlas with PVRTC file
TextureAtlas *textureAtlas = [TextureAtlas textureAtlasWithFile: @"atlastest.pvr" capacity:3];

// TileMapAtlas with PVR file
TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.pvr" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];

// LabelAtlas with PVR file

LabelAtlas *label = [LabelAtlas labelAtlasWithString:@"123 Test" charMapFile:@"tuffy_bold_italic-charmap.pvr" itemWidth:48 itemHeight:64 startCharMap:' '];

As you can see, the PVRTC support is transparent .
Using PVRTC files has the following benefits:

  • It reduces the loading time (less footprint)
  • It is faster, for it consumes less bandwidth
  • It is also faster, since it implies less texture switches because more textures can be in memory at the same time (I might be wrong on this one :)

To convert a PNG file to PVRTC use this step:

/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/texturetool -e PVRTC -f PVR --channel-weighting-linear --bits-per-pixel-4 -o test_image.pvr test_image.png

Edit: Fixed grammar errors

Gaining some FPS in your game


So, you want to gain some FPS in your game.
Here is the checklist:

  • Optimize Chipmunk. Follow Skorche’s (the author of Chipmunk) tips
  • Compile your code with Thumb support disabled
  • And from cocos2d v0.7 onwards you can use the Fast Director

To enable the Fast Director you need to call:
[Director useFastDirector];

before calling any other Director’s method.

Fast Director pros/cons:

  • Calls mainLoop as fast as it can
  • But no faster than 60 FPS (iPhone limitation)
  • Doesn’t support IntervalAnimation yet, so you can’t force it to, let’s say 30 FPS.

For example, the ChipmunkDemo example is running 10 FPS faster using the Fast Director.

In conclusion:

  • If don’t need a lot of speed, and you are OK with 30 FPS, then use the old Director since it supports the setIntervalAnimation method.
  • But if you want all the possible FPS then use the Fast Director

Remember: The more FPS, the more battery is consumed.

For more information regarding the FastDirector and how it was implemented see issue #145

[Edit]: Fixed grammar errors, added ‘in conclusion’

cocos2d for iPhone video #2

This video shows the new features of the soon-to-be released cocos2d for iPhone v0.7

cocos2d for iPhone v0.6.3 released

Download from:
http://cocos2d-iphone.googlecode.com/files/cocos2d-iphone-0.6.3.tar.gz

Changes from v0.6.2:

  • Actions: ScaleTo & ScaleBy supports X and Y factors (issue #156)
  • Actions: Added collections of Ease Actions (issue #157)
  • Chipmunk: cpFlaot is a float, not a double (issue #130)
  • CocosNode: fixed absolutePosition (issue #140)
  • CocosNode: unschedule timers only when running (issue #142)
  • CocosNode: prevents crash under certain circumstances while executing actions (issue #141)
  • Demos: Added Texture2dDemo example (issue #169)
  • Demos: SpritesDemo has an improved Accelerate example (issue #168)
  • Demos: ParticlesDemo has the Rain Particle example (issue #136)
  • Demos: Added EaseDemo showing all the ease capabilities (issue #158)
  • Director: allow cleanup when deallocing the director (issue #144)
  • Director: avoid useless GL commands when displaying FPS (issue #162)
  • Director: possibility to change the DepthBuffer size (issue #160)
  • Label: possibility to create Label without dimensions and aligment (issue #154)
  • Menu: MenuItemToggle supports assigning the selectedIndex (issue #152)
  • Menu: aligment takes into account if status bar is present (issue #131)
  • MenuItem: improved compiler warning (issue #147)
  • Misc: added ‘f’ to numbers so they are floats, not doubles (issue #130)
  • Particles: added ParticleRain (issue #136)
  • Sprites: fixed possible memory leaks (issue #139)
  • Particles: center of emitter can be moved independently from position (issue #138)
  • Texture2D: prevent allocating more memory than needed (issue #154)
  • TextureMgr: supports directories withing the image name (issue #151)
  • TileMapAtlas: fixed bug when using TGA files (issue #124)
  • TileMapAtlas: supports up to 255 chars (issue #153)

Compatibility:

  • It is 99% compatible with v0.6.2
  • The remaining 1% is that [menu alignItemsXXX] takes into account the presence of the StatusBar now

How to replace v0.6.2 (or older version):

  • Download v0.6.3
  • copy these directories to your game (replace the old ones)
  • -> cocos2d
  • -> cocos2d/Support
  • -> Chipmunk/src

New features:

  • EaseActions: See the new EaseDemo example
  • ParticleRain: See the ParticleDemo example
  • New way to create Labels: See the Texture2dDemo

cocos2d for iPhone v0.6.3 released

Download from:
http://cocos2d-iphone.googlecode.com/files/cocos2d-iphone-0.6.3.tar.gz

Changes from v0.6.2:

  • Actions: ScaleTo & ScaleBy supports X and Y factors (issue #156)
  • Actions: Added collections of Ease Actions (issue #157)
  • Chipmunk: cpFlaot is a float, not a double (issue #130)
  • CocosNode: fixed absolutePosition (issue #140)
  • CocosNode: unschedule timers only when running (issue #142)
  • CocosNode: prevents crash under certain circumstances while executing actions (issue #141)
  • Demos: Added Texture2dDemo example (issue #169)
  • Demos: SpritesDemo has an improved Accelerate example (issue #168)
  • Demos: ParticlesDemo has the Rain Particle example (issue #136)
  • Demos: Added EaseDemo showing all the ease capabilities (issue #158)
  • Director: allow cleanup when deallocing the director (issue #144)
  • Director: avoid useless GL commands when displaying FPS (issue #162)
  • Director: possibility to change the DepthBuffer size (issue #160)
  • Label: possibility to create Label without dimensions and aligment (issue #154)
  • Menu: MenuItemToggle supports assigning the selectedIndex (issue #152)
  • Menu: aligment takes into account if status bar is present (issue #131)
  • MenuItem: improved compiler warning (issue #147)
  • Misc: added ‘f’ to numbers so they are floats, not doubles (issue #130)
  • Particles: added ParticleRain (issue #136)
  • Sprites: fixed possible memory leaks (issue #139)
  • Particles: center of emitter can be moved independently from position (issue #138)
  • Texture2D: prevent allocating more memory than needed (issue #154)
  • TextureMgr: supports directories withing the image name (issue #151)
  • TileMapAtlas: fixed bug when using TGA files (issue #124)
  • TileMapAtlas: supports up to 255 chars (issue #153)

Compatibility:

  • It is 99% compatible with v0.6.2
  • The remaining 1% is that [menu alignItemsXXX] takes into account the presence of the StatusBar now

How to replace v0.6.2 (or older version):

  • Download v0.6.3
  • copy these directories to your game (replace the old ones)
  • -> cocos2d
  • -> cocos2d/Support
  • -> Chipmunk/src

New features:

  • EaseActions: See the new EaseDemo example
  • ParticleRain: See the ParticleDemo example
  • New way to create Labels: See the Texture2dDemo