To create alert view in cocos2d

Add this code in your class:

-(void)newLocalScore {

UIAlertView* dialog = [[UIAlertView alloc] init];

[dialog setDelegate:self];

[dialog setTitle:@"Online Access"];

[dialog setMessage:@"Do you want to connect to the online ranking?"];

[dialog addButtonWithTitle:@"Yes"];

[dialog addButtonWithTitle:@"No"];

[dialog show];

[dialog release];

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex


if(buttonIndex==0) {

//do stuff



To detect shake in cocos2d

Add the following lines to the layer class :

self.isAccelerometerEnabled = YES;

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1/60];

shake_once = false;

Then implement this function in the layer class:

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

float THRESHOLD = 1.5;

if (acceleration.x > THRESHOLD || acceleration.x THRESHOLD || acceleration.y THRESHOLD || acceleration.z < -THRESHOLD) {

if (!shake_once) {

shake_once = true;



else {

shake_once = false;



Liquid,lens and wave effects in cocos2d

These effects are like any other action, it is executed by the do: selector.


// Create an sprite
CCSprite *star = [Sprite spriteWithFile:@"star.png"];
// Tell the sprite to execute the Liquid effect
[star do: [Liquid actionWithWaves:4 amplitude:20 grid:ccg(10,10) duration:5]];
Like any other grid action,this effect receives the grid parameter. We can adjust the quality of the effect by increasing the size of the grid.

// 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 and repeat it forever
[star do: [RepeatForever actionWithAction: [Sequence actions: waves, lens, nil]]];

Tiled Maps In Cocos2D

Tiled Maps

There are 2 ways of creating tiled maps in cocos2d.

  • by using the TMX Tile Map format (newer, more flexible, recommended)
  • by using the PGU Tile Map format (older, deprecated)


cocos2d supports the following TMX maps:

  • Orientation:

    • Orthogonal maps
    • Isometric maps
    • Hexagonal maps (edges on left-right. edges at top-bottom are not supported… it seems that Tileddoesn’t support them either)
  • Tiles:

    • Embedded tiles are NOT supported (i.e., tilesets with embedded images).
    • Only embedded tilesets are supported (i.e., the tileset is embedded, but not its images).
    • supports at most 1 tileset per layer.
  • Layers:

    • You can have as many layers are you want
    • Each layer will be represented internally by a CCTMXLayer (which is a subclass of CCSpriteSheet)
    • Each tile will be represented by an CCSprite (its parent will be the CCTMXLayer)
  • Object Groups:

    • Tiled objectGroups are supported as well
      How to create embedded tilesets with external images

cocos2d doesn’t support embedded images in tilesets (but requires tilesets themselves to be embedded in the map file). Instead you should create a sprite sheet image (AKA: Texture Atlas) by yourself.

Setting the Tiled preferences

Tell tiled to NOT save the tileset with embedded images:

$ cd bin/tiled-0.7.2/
$ java -jar tiled

Once in tiled, you should do:

  • Edit → Preferences → Saving
  • Layer Options:

    • Use binary encoding: ON (“text” encoding is not supported by cocos2d)
    • Compress layer data: ON (non-compressed data is also supported)
  • Tileset Options:

    • Embed images (PNG): OFF (Embedding images is not supported)

       How to create a TMX node

CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"hexa-test.tmx"];
[self addChild:map];

All the tiles by default will be aliased. If you want to create anti-alias tiles, you should do:

// create a TMX map
CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"orthogonal-test2.tmx"];
[self addChild:map];

// iterate over all the "layers" (atlas sprite managers)
// and set them as 'antialias' 
for( CCTMXLayer* child in [map children] ) {
    [[child texture] setAntiAliasTexParameters];

How to get/add/delete/modify a tile

To obtain a tile (CCSprite) at a certain coordinate

CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"orthogonal-test2.tmx"];

CCTMXLayer *layer = [map layerNamed:@"Layer 0"];


CCSprite *tile = [layer tileAt:ccp(0,63)];

tile.anchorPoint = ccp(0.5f, 0.5f);

To obtain a tile's GID at a certain coordinate

CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"orthogonal-test2.tmx"];

CCTMXLayer *layer = [map layerNamed:@"Layer 0"];


unsigned int gid = [layer tileGIDAt:ccp(0,63)];

To set a new tile’s GID’s at a certain coordinate

CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"orthogonal-test2.tmx"];

CCTMXLayer *layer = [map layerNamed:@"Layer 0"];


[layer setTileGID:gid2 at:ccp(3,y)];

To remove a tile at a certain coordinate

CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"orthogonal-test2.tmx"];

CCTMXLayer *layer = [map layerNamed:@"Layer 0"];


[layer removeTileAt:ccp(15,15)];

To iterate a Layer

CCTMXTiledMap *map = [CCTMXTiledMap tiledMapWithTMXFile:@"orthogonal-test2.tmx"];

CCTMXLayer *layer = [map layerNamed:@"Layer 0"];


CGSize s = [layer layerSize];

for( int x=0; x<s.width;x++) {

for( int y=0; y< s.height; y++ ) {

unsigned int tmpgid = [layer tileGIDAt:ccp(x,y)];

[layer setTileGID:tmpgid+1 at:ccp(x,y)];



Cocos2d-iPhone Sprite Rotation to an Arbitrary Point

(void)rotateSourceSprite:(CCSprite*)sourceSprite toFaceTargetSprite:(CCSprite*)targetSprite{
CGPoint difference=ccpSub(sourceSprite.position,targetSprite.position);
CGFloat rotationRadians=ccpToAngle(difference);
CGFloat rotationDegrees=-CC_RADIANS_TO_DEGREES(rotationRadians);
 CGFloat rotateByDegrees=rotationDegrees-sourceSprite.rotation;

CCRotateBy* turnBy=[CCRotateBy actionWithDuration:0.5f angle:rotateByDegrees];
CCEaseIn*ease=[CCEaseIn actionWithAction:turnBy rate:4];
[sourceSprite runAction:ease];

Random placement of objects in a scene without intersecting using arrays



// initialising counter

int option;




if(optionsArray.count > 0)


[optionsArray removeAllObjects];


if(xarray.count > 0)


[xarray removeAllObjects];


if(yarray.count > 0)


[yarray removeAllObjects];




do {

[self getPosition];

[self check_position];

} while (position_flag==1);

NSLog(@"startFunction  %d///////%d",xpos,ypos);

// add positions in arrays

[xarray addObject:[NSString stringWithFormat:@"%d",xpos]];

[yarray addObject:[NSString stringWithFormat:@"%d",ypos]];

clouds[i] = [CCSprite spriteWithFile:@"cloud222.png"];

clouds[i].tag = cloud_tag;


clouds[i].position = ccp(xpos,ypos);

s2=[clouds[i] contentSize];

[self addChild:clouds[i] z:500];


do {


} while ([optionsArray containsObject:[non_repeat_random_numbers objectAtIndex:option]]);

[optionsArray addObject:[non_repeat_random_numbers objectAtIndex:option]];

word=[non_repeat_random_numbers objectAtIndex:option];

label=[CCLabelTTF labelWithString:word fontName:@"Marker Felt" fontSize:28];


label.color = ccc3(100,10,255);


[clouds[i] addChild:label];


















int k2=0;

while(k2<[xarray count])


x1=[[xarray objectAtIndex:k2] intValue];

y1=[[yarray objectAtIndex:k2] intValue];

if(x1 <= (xpos+50) && x1 >= (xpos-50)  && y1<=(ypos+50) && y1>=(ypos-50))














Changing the Font size of UISegmentedControl Segment in Xcode

Consider a UISegmentedControl object as follows :

UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"ON",@"OFF",nil]];
segment.selectedSegmentIndex = 0;
[self changeUISegmentFont:segment]; // Call this method to edit the label of the segment with the UISegmentedControl object as parameter. The method definition is given below.

// Method Definition

-(void) changeUISegmentFont:(UIView*) myView {

if ([myView isKindOfClass:[UILabel class]]) {  // Getting the label subview of the passed view

UILabel* label = (UILabel*)myView;

[label setTextAlignment:UITextAlignmentCenter];

[label setFont:[UIFont boldSystemFontOfSize:14]]; // Set the font size you want to change to


NSArray* subViewArray = [myView subviews]; // Getting the subview array

NSEnumerator* iterator = [subViewArray objectEnumerator]; // For enumeration

UIView* subView;

while (subView = [iterator nextObject]) { // Iterating through the subviews of the view passed

[self changeUISegmentFont:subView]; // Recursion



Making UIImageView Round Cornered with Border Programmatically in Xcode

The following code will make the UIImageView round cornered with border to it :

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(42, 2, 55, 26)]; // Creating a UIImageView object

imgView.image = [UIImage imageNamed:@"myImage.png"]; // Adding image to the UIImageVIew object

imgView.contentMode = UIViewContentModeScaleAspectFill; // Setting the content mode for the UIImageView

imgView.clipsToBounds = YES;

// For rounded corners:

imgView.layer.cornerRadius = 6.0; // Setting the corner radius

imgView.layer.masksToBounds = YES; // For enabling masking


//For adding border

imgView.layer.borderColor = [UIColor whiteColor].CGColor; // Setting the border color

imgView.layer.borderWidth = 2.0; // Setting the border width

CCSprite to CCTexture2d conversion

To get texture and sprite from an image using the flowing code:
NSString* file = @"myImage.png";
CCTexture2D* texture = [[CCTextureCache sharedTextureCache] addImage:file];
CGSize texSize = texture.contentSize;
CGRect texRect = CGRectMake(0, 0, texSize.width, texSize.height);
CCSpriteFrame* frame = [CCSpriteFrame frameWithTexture:texture rect:texRect];