Category Archives: Cocos2D

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to move a body manually in Box2D? or Give a force to a body in Box2D, iPhone.

This is a sample code to move a body in Box2D .
First you have to make a body with variable name “moving_rec” and call the below function in a schedular at regular intervals.

-(void) moveBody{
       b2Vec2 force = b2Vec2(0,0);
       force = b2Vec2(0,3);       //Giving the x an y to negative will move the body in opposite direction.
       moving_rec->SetLinearVelocity(force); //set Linear velocity for moving in a constant speed.
}

Please leave your comments on this post.

Pause And Resume iPhone Game Using Cocos2D

More than usually we need to apply the functions of Pause and Resume/Play for our games. In Mac’s cocos2D programming it’s more than simple. Simply use the following code for Pause & Resume where ever you want!

/*For Pausing the game*/

[[CCDirector sharedDirector] pause];
[self pauseSchedulerAndActions]; //Call for pausing all schedulers and actions

/*For Resuming/Playing back the game*/

[[CCDirector sharedDirector] resume];
[self resumeSchedulerAndActions]; // Call for resuming all schedulers and actions

:)

Using of CCWaves in iPhone

CCWaves is one of the interesting functionalities in Cocos2D iphone.
Check out this following snippet to see how it works.

id my_wavesAction = [CCWaves actionWithWaves:7 amplitude:25 horizontal:NO
                                                               vertical:YES grid:ccg(15,10) duration:10];
[my_sprite runAction: [CCRepeatForever actionWithAction:my_wavesAction n]];

Please leave your valuable comments on this post………………….

How to get Device Orientation in Cocos2D, iPhone in Objective C?

Hello all……
We may need to know that what is your current device orientation.
Using the below code you can do this.

if([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortrait) {
            NSLog(@"Device is now in Portrait Mode");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeLeft) {
            NSLog(@"Device is now in LandscapeLeft Mode ");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeRight) {
            NSLog(@"Device is now in LandscapeRight Mode");
}
else if([[UIDevice currentDevice]orientation] ==
  kCCDeviceOrientationPortraitUpsideDown) {
            NSLog(@"Device is now in PortraitUpsideDown Mode");
ss="Apple-style-span" style="font-weight: normal;">
}

Note: If you have to explicitly set the orientation of your phone to any of the above you can set this in the appDelegate.m file. You can put an “||” (OR) symbol in between to set more than one.

Please leave your valuable comments if this post was useful…..

Simulate a Balloon in Box2D, iPhone or ANDROID

Hello………
Sometimes you may want your body to act against the gravity of the world.
One method to do this is described below.
First what you have to do is to make a body in the shape of a circle and give it the image of a balloon as the userdata.

Then in the tick function write this code.
This method of applying the force is called “The antagonist forces method”
By this method we are giving an upward force to only our balloon body irrespective of the gravitational force.
After running the code you will see your body floating in air like a balloon.

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
   {
        if (b->GetUserData() != NULL) {
               if (b==baloonBody) {
                         b->ApplyForce( b2Vec2(0.0,9.8*b->GetMass()),b->GetWorldCenter()); // here 0.0 is x, 9.8 is y (the gravity)
               }
         }
   }

Note: Try to change the value 9.8 to higher if you have given your world’s gravity as 9.8. It will produce a balloon effect.
Please leave your comments if this post was useful……….

Sprite Animations Without Sprite Sheets

You can simulate any animations if you have a sequence of images which makes the illusion of that
animations and rendering those images to the screen. In cocos2D it can be done in two ways, with sprite sheet
animation and without sprite sheets. Here we are going to see how it can be done with out sprite sheet.


CCAnimation *sitDown = [CCAnimation animationWithName:@"sitDown" delay:0.1f];

[sitDown addFrameWithFilename:@"sit1.png"];
[sitDown addFrameWithFilename:@"sit2.png"];

[mySprite addAnimation:sitDown];

id sitAction = [CCAnimate actionWithAnimation:sitDown restoreOriginalFrame:YES];

[yourSprite runAction:sitAction];

Here CCAnimation holds a series of images known as Frames and CCAnimate is simply the action which will run the
CCAnimation. Simple.

Suppose that we have two images named, sit1.png and sit2.png which simulates a sitting animation of our sprite. First
we have added that images/frames to our CCAnimation object sitDown. Then we CCAnimate our CCAnimation frames and
deploy those actions to our sprite. We can set the delay time between the individual frames in CCAnimation. Also we can restore the original image before sprite animation after animatin completes or not!That’s it.

We will later see in here how Sprite Animations can be done by using Sprite Sheets. Keep in touch.

:)

How to use CCProgressTimer in Cocos2D to show progress?

The progress timer takes a
sprite and, based on a percentage, displays only a part of it to visualize some kind of
progress in your game.

CCProgressTimer* timer = [CCProgressTimer progressWithFile:@"progress.png"];
timer.type = kCCProgressTimerTypeRadialCCW;
timer.percentage = 0;
[self addChild:timer z:1 tag: my_tag];
// The update is needed for the progress timer.
[self scheduleUpdate];

You can choose between radial, vertical, and horizontal progress timers. But the timer doesn’t update itself. You have to change the timer’s percentage value frequently to update the progress.

Creating Menu in Iphone Cocos2D or Box2D?

Use CCMenuItemSprite and CCMenu in iPhone to create menu.

-(void) setUpMenu
{
	 CCSprite *Home1 = [CCSprite spriteWithFile:@"Home1.png"];
	 CCSprite *Home2 = [CCSprite spriteWithFile:@"Home1.png"];
	 Home2.opacity = 100;

	 CCSprite *Levels1 = [CCSprite spriteWithFile:@"levels2.png"];
	 CCSprite *Levels2 = [CCSprite spriteWithFile:@"levels2.png"];
	 Levels2.opacity = 100;

	 CCSprite *Refresh1 = [CCSprite spriteWithFile:@"refresh.png"];
	 CCSprite *Refresh2 = [CCSprite spriteWithFile:@"refresh.png"];
	 Refresh2.opacity = 100;

	 CCSprite *go_back1 = [CCSprite spriteWithFile:@"back2.png"];
	 CCSprite *go_back2 = [CCSprite spriteWithFile:@"back2.png"];
	 go_back2.opacity = 100;

	 CCMenuItemSprite  *top_menuSprite1 = [CCMenuItemSprite itemFromNormalSprite:Home1 selectedSprite:Home2 target:self selector:@selector(goHome)];
	 CCMenuItemSprite  *top_menuSprite2 = [CCMenuItemSprite itemFromNormalSprite:Levels1 selectedSprite:Levels2 target:self selector:@selector(goToLevelSelection)];
	 CCMenuItemSprite  *top_menuSprite3 = [CCMenuItemSprite itemFromNormalSprite:Refresh1 selectedSprite:Refresh2 target:self selector:@selector(reloadGame)];
	 CCMenuItemSprite  *top_menuSprite4 = [CCMenuItemSprite itemFromNormalSprite:go_back1 selectedSprite:go_back2 target:self selector:@selector(menuGoBack)];
	 top_menu = [CCMenu menuWithItems:top_menuSprite1,top_menuSprite2, top_menuSprite3 ,top_menuSprite4, nil];
	 [top_menu  alignItemsVerticallyWithPadding:10.0f];
	 top_menu.position = ccp(240,160);

	 [self addChild:top_menu z:2];
}

call this function to set up the menu for your home page in your iPhone game or you can change this code directly to ANDROID and it will work.
Make sure you have all the images mentioned in the above example.
This menu will appear on the centre of the screen in Landscape mode.

Angry Birds Again, Angry Birds Space, the new Angry Birds coming.

We know Angry Birds have conquered almost all tablets and now the completely new edition is launching this March.
Acoording to the reports the new game will be launched on March.

Angry Birds Space already has an official website with an image of a slingshot on the Moon overlooking Earth.


The official blog spot says that

Angry Birds Space is a “completely new game with innovative new gameplay, but with some of the familiar Angry Birds elements that fans already know and love.”

Check out the official Blog site here.

How to open browser from android cocos2D Application?

This code snippet helps you to open browser in android cocos2D application

public void openBrowser(){
		CCDirector.sharedDirector().getActivity().runOnUiThread(new Runnable() {
		    public void run() {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
				CCDirector.sharedDirector().getActivity().startActivity(browserIntent);
		}});
	}

Call this function anywhere inside your cocos2D project to open the browser with the corresponding URL.

How to save data or score in Android Cocos2D?

Hello Friends
Today I will show you how to save data in cocos2D android in a database and reload it when the game starts.
This has been always a problem withe game developers for cocos2D android.
I will show you a way to save almost any number of data in a database using SQlite in android.

Check these examples for how to use SQlite databases in android
1. Working with SQLite Database in ANDROID.
2. Using SQLite in ANDROID, A really simple example.

First thing you need to know is cocos2d.
Downlod a sample project for cocos2D from here and copy the libraries into your project
Assuming all are familiar with Cocos2D. I am starting this tutorial.

Create a fresh project named SaveDataDemo.
then create a class named SQlite.java and copy this code into it.
This file contains the table definition and methods for accessing the data in the table. All you need is call these functions in your main file and insert, update or get the data from the database.

SQlite.java

package com.coderzheaven.pack;

import java.util.Set;
import java.util.Map.Entry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class MyTable
{
	 private String TABLE_NAME = "my_table";
	 int DATABASE_VERSION = 1;
	 private String _ID = "id";
	 private String _SCORE = "score";

	public String getTableName(){			return TABLE_NAME;}
	public int getDatabaseVersion()	{		return DATABASE_VERSION;}

	public String getID()		{		return _ID;			}
	public String getScore()	{		return _SCORE;		}

	public String getDatabaseCreateQuery()
	{
		final String DATABASE_CREATE =
		    "create table IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, "
		    + _SCORE + " TEXT NOT NULL)";

		return DATABASE_CREATE;

	}
}

class dbOperation
{
		static String DB_TABLE ;
		static int DB_VERSION = GlobalClass.DATABASE_VERSION;
		static String[] DATABASE_CREATE;
	    private Context context;
	    private DatabaseHelper DBHelper;
	    private SQLiteDatabase db;

	    public dbOperation(Context ctx,String[] query)
	    {
	    	this.context = ctx;
 	        DATABASE_CREATE = query;
 	        DBHelper = new DatabaseHelper(context);
	    }
	    public dbOperation(Context ctx)
	    {
	    	this.context = ctx;
	    	DBHelper = new DatabaseHelper(context);
	    }

	    public dbOperation(String tablename)  //for inner calling
	    {
	    	DB_TABLE = tablename;
	    	DBHelper = new DatabaseHelper(context);
	    }

		public dbOperation open() throws SQLException
	    {
	        db = DBHelper.getWritableDatabase();
	        return this;
	    }
	    public void close()
	    {
	        DBHelper.close();
	    }
	    private static class DatabaseHelper extends SQLiteOpenHelper
	    {
	        DatabaseHelper(Context context)
	        {
	            super(context, GlobalClass.DBNAME, null, DB_VERSION);
	        }
	        public void onCreate(SQLiteDatabase db)
	        {
	            try
	            {
	            	for (String s  : DATABASE_CREATE)
	            	{
	            		db.execSQL(s);
					}
				}
	            catch (Exception e) {
					System.out.println("Error creating items Per screen in the constructor" + e.getMessage());
				}
	        }
	        public void onUpgrade(SQLiteDatabase db, int oldVersion,
	        int newVersion)
	        {
	        	db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
	            onCreate(db);
	        }
	    }

	    public long insertTableData(String tablename,ContentValues values)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	ContentValues initialValues2 = new ContentValues();
	        Set<Entry<String, Object>> s =  values.valueSet();
	        String new_val = "";
	        for (Entry<String, Object> entry : s) {
	            new_val = values.getAsString(entry.getKey());
	            initialValues2.put(entry.getKey(), new_val);
	        }
	        return db.insert(DB_TABLE, null, initialValues2);
	    }
	    public boolean deleteTableData(String tablename,String condition)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	return db.delete(DB_TABLE, condition, null) > 0;
	    }
	    public Cursor getAllTableData(String tablename,String[] fields)  throws SQLException
	    {
	    	DB_TABLE = tablename;
				return db.query(DB_TABLE, fields,null, null, null, null, null);
	    }
	    public Cursor getTableRow(String tablename,String[] dbFields, String condition,String order,String limit) throws SQLException
	    {
	    	DB_TABLE = tablename;
	        Cursor mCursor =    db.query(false, DB_TABLE, dbFields,condition,
	                			null,null,null, order, limit);

	        if (mCursor != null) {
	            mCursor.moveToFirst();
	        }
	        return mCursor;
	    }
	    public boolean updateTable(String tablename,ContentValues args,String condition)
	    {
	    	DB_TABLE = tablename;
	    	return db.update(DB_TABLE, args,condition , null) > 0;

	    }
	    public int lastInsertedID(String tablename)
	    {
	    	int retVar=0;
	    	Cursor mCursor = db.rawQuery("select max(id) from "+tablename, null);

			if (mCursor != null) {
				mCursor.moveToFirst();
				retVar =Integer.parseInt(mCursor.getString(0));
			}
			mCursor.close();
			mCursor.deactivate();
			return retVar ;
	    }
}

Now create a file named “GameLayer.java” file and copy this code into it.
GameLayer.java

package com.coderzheaven.pack;

import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;

import android.content.ContentValues;
import android.database.Cursor;
import android.view.MotionEvent;

public class GameLayer extends CCColorLayer
{
	protected CCLabel _label = null;
	CGSize winSize = CCDirector.sharedDirector().displaySize();
	int myscore = 0;

	public static CCScene scene()
	{
		CCScene scene = CCScene.node();
		CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
		scene.addChild(layer);
		return scene;
	}

	protected GameLayer(ccColor4B color)
	{
		super(color);
		this.setIsTouchEnabled(true);
		DBOperations();
	}

	public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

	public void createAndInitializeTables(){
        try{
        	MyTable mytable = new MyTable();
        	String[] tableCreateArray = {mytable.getDatabaseCreateQuery()};
    		dbOperation operation = new dbOperation(CCDirector.sharedDirector().getActivity(),tableCreateArray);
			operation.open();
			operation.close();
        }catch(Exception e){
           System.out.println("Error creating table " + e.getMessage());
        }
        System.out.println("Table successfully created!!");
	}
	public int getDataFromTable(){
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		MyTable mytable = new MyTable();
		int score = 0;
		String  condition2 = mytable.getID() +" = 1 ";
        String[] dbFields4 = {mytable.getScore()};
        Cursor cursor =  operationObj.getTableRow(mytable.getTableName(),dbFields4,condition2,mytable.getID() + " ASC ",1 +"");
        if(cursor.getCount()>0)
        {
        	 cursor.moveToFirst();
        	 do{
        		 score = cursor.getInt(0);
        	 }while(cursor.moveToNext());
        }
        cursor.close();
		cursor.deactivate();
		operationObj.close();

		return score;
	}
	public void insertData(int score){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),score+"");
        operationObj.insertTableData(mytable.getTableName(),initialValues);
        int maxID = operationObj.lastInsertedID(mytable.getTableName());
        System.out.println("LAST INSERTED ID : " + maxID);
        operationObj.close();
	}
	public void updateTable(int scr){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
        String condition = mytable.getID() + " = 1";
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),scr+"");
        operationObj.updateTable(mytable.getTableName(),initialValues,condition);
        operationObj.close();
	}
	public void showLabel(int scr){

		if(_label != null){
			this.removeChild(_label,true);
		}
		_label = CCLabel.makeLabel("Score : " + scr, "Verdana", 20);
		_label.setColor(ccColor3B.ccBLACK);
		_label.setPosition(5 5f, winSize.height - 15);
		addChild(_label);
	}
	public void addAndroid(){
		CGSize winSize = CCDirector.sharedDirector().displaySize();
		CCSprite player = CCSprite.sprite("android.png");
		player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f, winSize.height / 2.0f));
		addChild(player);

		CCMoveTo actionMove = CCMoveTo.action(3, CGPoint.ccp(winSize.getWidth(), winSize.getHeight()/2.0f));
		CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
		CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);

		player.runAction(actions);
	}

	public void spriteMoveFinished(Object sender)
	{
		CCSprite sprite = (CCSprite)sender;
		this.removeChild(sprite, true);
		myscore++;
		updateTable(myscore);
		showLabel(myscore);
		addAndroid();
	}
	@Override
	public boolean ccTouchesBegan(MotionEvent event)
	{
		return true;
	}
}

Note : copy a file named “android.png” into the assets folder.

Now create a file named “GlobalClass.java” and copy this code into it.
GlobalClass.java

package com.coderzheaven.pack;

public class GlobalClass
{
	  public static String DBNAME = "mytest.db";
	  public static final int DATABASE_VERSION = 1;
}

Now this is the main file that calls this gamelayer which is named “SaveDataDemo.java”

package com.coderzheaven.pack;

import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class SaveDataDemo extends Activity
{
	protected CCGLSurfaceView _glSurfaceView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		_glSurfaceView = new CCGLSurfaceView(this);
		setContentView(_glSurfaceView);
	}

	@Override
	public void onStart()
	{
		super.onStart();
		CCDirector.sharedDirector().attachInView(_glSurfaceView);
		CCDirector.sharedDirector().setDeviceOrientation(CCDirector.kCCDeviceOrientationLandscapeLeft);
		CCDirector.sharedDirector().setDisplayFPS(true);
		CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
		CCScene scene = GameLayer.scene();
		CCDirector.sharedDirector().runWithScene(scene);
	}

	@Override
	public void onPause()
	{
		super.onPause();
		CCDirector.sharedDirector().pause();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		CCDirector.sharedDirector().resume();
	}

	@Override
	public void onStop()
	{
		super.onStop();
		CCDirector.sharedDirector().end();
	}
}

Inside the GameLayer class check these functions that loads the data from the database or insert or update the database.

public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

Here are the screenshots.





Download the complete source code from here.

If you find this post useful please leave your valuable comments and +1 this post to share more and give me encouragement for future posts.

Join the Forum discussion on this post

How to Show Cocos2D Particle Effects Repeatedly ?

Hi,

For showing particle effects repeatedly in Cocos2D, use the sample code.

CCParticleSystemQuad *yourParticleEffect = [CCParticleSystemQuad particleWithFile:@"yourEffect.plist"];

[self addChild:yourParticleEffect z:5];

This will show the effect ‘yourEffect’ repeatedly in your game. :)

How to open URL from iPhone application ?

Hi,

For opening a Web Link/URL from an iPhone application, follow the two simple steps.
Step 1 :
Create an NSURL object and initialize it with your URL string

 NSURL *myURL = [NSURL URLWithString:@"http://www.coderzheaven.com/"];

;

Step 2 :
Use the openURL method by passing your NSURL object

[[UIApplication sharedApplication] openURL: myURL];

Done. :)

How to Fix ‘Warning : Multiple Build Commands For Output File' ?

Hi,

The following warning, ‘Multiple Build Commands For Output File’ occurs when you try to delete resource files by ‘delete reference’ other than the correct method of‘move to trash’ while deleting files from ‘Resources’ folder of your project. Therefore the Copy Bundle Resources still holds the references of the same file you have deleted and it shows the multiple build commands for the output file after you added the same files over again.

How to Fix? :

Go to the Targets->YourProject->Copy Bundle Resources

From ‘Copy Bundle Resources’ delete those files whose reference are still there or files which shows the warning.

Here ‘YourProject’ is your project name.
:)

How to remove duplicates from NSMutableArray ?

Hi,

For removing or deleting duplicates from a NSMutableArray , use the following lines of code. It will simply check for duplicates elements and get it deleted or removed.


NSArray *tempArr= [urArray copy];

NSInteger idx = [tempArr count] - 1;

for (id object in [tempArr reverseObjectEnumerator]) {

     if ([urArray indexOfObject:object inRange:NSMakeRange(0, index)] !=NSNotFound) {

           [urArray removeObjectAtIndex:idx];
     }

idx--;

}
[tempArr release];

:)

How to set iPhone/iPad table view transparent ?

Hi,

In order to simply set the iPhone/iPad table view transparent use the following line of code.

urTblView.backgroundColor = [UIColor clearColor];

Here ‘urTblView’ is the table view that you want to make transparent. Try it out. This single line will make your table view transparent and looks better.
:)

How to change z order value of a sprite in Cocos2D ?

Hi,

Sometimes during the execution of program you may need to change the z order value of sprite for better working. Use the following sample of code to change the z order value of a sprite in Cocos2D/Box2D iPhone programming.

CCSprite *urSprite = [CCSprite spriteWithFile:@"coderzheavenLogo.png"];
urSprite.position = ccp(240,160);
//First setting the z value to 1
[self addChild:urSprite z:1];
.
.
.
.
.
//After some other executions are over setting z value to 7
[self reorderChild:urSprite z:7];

:)

How to make a sprite visible and invisible in Cocos2D ?

Hi,

In order to make a sprite completely invisible , use the following code while using Cocos2D, this code will set the visibility of your sprite to zero.

urSprite.visible = 0; 

In order to make a sprite completely visible, use the following code while using Cocos2D, this code will set the visibility of the sprite back to one.

urSprite.visible = 1; 

:)