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.
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
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…..
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.
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.
Here is a simple example showing alert in android cocos2D.
For this I am using an example from my previous android cocos2D tutorial..
So please read that tutorial before reading this because the I am using the classes and files from it.
I am only changing the Gamelayer.java file to show an Alert Dialog when the sprite move is finished.
Check the showAlert() function which will show the Alert.
Here is the modified 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.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
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(55f, 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);
showAlert();
//addAndroid();
}
public void showAlert(){
CCDirector.sharedDirector().getActivity().runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(CCDirector.sharedDirector().getActivity());
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CCDirector.sharedDirector().getActivity().finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
@Override
public boolean ccTouchesBegan(MotionEvent event)
{
return true;
}
}
Please copy all other files from this project before proceeding.
A sample project is available for download for this tutorial.

Alert in android cocos2D
Hi,
For calling a function after a definite time interval in Cocos2D, use the following code.
[self performSelector:@selector(yourFunction) withObject:nil afterDelay:7.0];
this will call the function ‘yourFunction’ after 7 seconds.
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.
Hi,
How can you detect single/double/triple taps in iPhone using Objective C?
Use the following code to detect single or multiple taps in iPhone/iPad/iPod.
The code can also be used with Cocos2D & Box2D.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *urtouch = [touches anyObject];
NSUInteger urtapCount = [urtouch tapCount];
switch (urtapCount) {
case 1:
NSLog(@"Single Tap Detected!");
break;
case 2:
NSLog(@"Double Tap Detected!");
break;
case 3:
NSLog(@"Triple Tap Detected!");
break;
default :
break;
}
}
Try it out! You can even detect Quadrup!
Hi,
Sometimes you may want to detect shake gesture in iPhone using your programs. But how can you detect shake gesture in iPhone? Shake gesture in iPhone can be detected by using the accelerometer. The following lines of code can be used for detecting the shake gesture in iPhone. You can use these lines of code in your cocos2D applications/games.
First of all you MUST enable accelerometer in the init function
isAccelerometerEnabled = YES;
Then use the following function to detect the shake gesture.
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
if(abs(acceleration.x-oldX )>0.7 || abs(acceleration.y-oldY)>0.7)
{
NSLog(@”Yupie! Shake detected!”);
}
oldX = acceleration.x;
oldY = acceleration.y;
}
Here oldX & oldY are variables that store accelerometer values and 0.7 is the value you are giving to check for shake gesture. That’s it.
Hi,
If you are a game developer and you are using box2D for real world simulations, you would probably need a particular body to be removed from the box2D world! But how can you remove box2D body from world ? See the following sample code which does the same.
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//Getting Touch Locations
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
//Converting to cocos2D positioning
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
//Getting body list from world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {
//Getting Fixture from the bodies
b2Fixture *bf1 = b->GetFixtureList();
//Checking whether the fixture contains touch location!
if (bf1->TestPoint(locationWorld)) {
//If YES assigning user data to a sprite tempSprite
CCSprite *tempSprite = (CCSprite *) b->GetUserData();
//Checking whether the user data sprite tag is 7
if (tempSprite .tag==7) {
//If YES then remove the sprite & the body!
[self removeChild:tempSprite cleanup:YES];
world->DestroyBody(b);
}
}
}
}
Here tag 7 is what we previously assigned for the sprite corresponding to the body’s user data!
Hi,
In certain situations you may need to make visible or invisible certain sprites. But how to set a sprite visible and invisible in Cocos2D? See the following Cocos2D code.
//Set the sprite's visible value to 1 to make it visible
yourSprite.visible = 1;
//Set the sprite's visible value to 0 to make it invisible
yourSprite.visible = 0;
Hi,
There may arise some situations where you need to change the z value of a particular sprite during an action in Cocos2D. So how can you do that? See the following lines of code.
CCSprite *sample= [CCSprite spriteWithFile:@"trialImage.png"];
sample.position = ccp(160,240);
[self addChild:sample z:1];
/* Some of your actions goes here! */
[self reorderChild:sample z:9];
This will re order the sprite’s tag to 9 from 1 after ‘your actions’.
Hi,
In one of our previous post we have discussed how to animate sprite sheet in cocos2D.
In some cases you may need to stop the sprite sheet animation abruptly. How to do that?
Here the way to do that. Use the following.
[spriteName stopAction:spriteNameAction];
where spriteName is the name of your sprite & spriteNameAction is the name of your sprite sheet animation action.
Hi,
While using Box2D , in many cases you may need to connect two bodies together. But the collision between them during motion is not what you preferred! So how can you prevent those bodies being connected in Box2D from collision?
Use the line of code to prevent the collision.
jointDef.collideConnected = false;
Hi,
Suppose you want to copy a sprite image to another new sprite while using cocos2D. What you do?
See the following code…
Let oldSprite be your first sprite
CCSprite *oldSprite = [CCSprite spriteWithFile:@"ImgOne.png"];
And newSprite be your second sprite
CCSprite *newSprite = [CCSprite spriteWithTexture:[oldSprite texture]];
That’s it! Done! Now newSprite too contain ImgOne as Sprite.
This simple code plays a music……..
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@”my_music.mp3″];
For stopping the music use this…….
[[SimpleAudioEngine sharedEngine]stopBackgroundMusic];
To pause the music use this line of code…..
[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
For an interactive game building using Box2D, collision detection of Box2D bodies is necessary. There is an easy way to implement collision detection in Box2D.
For checking whether two bodies have collided with each other in Box2D while using it with cocos2D, then use the following lines of code where ever you want to check collision.
if((contact.fixtureA == sourceFixture && contact.fixtureB == destinationFixture) ||
(contact.fixtureA == destinationFixture && contact.fixtureB == sourceFixture ))
{
//What you want to do after checking the collision?!!!
//That lines of code goes here!
//Simple and Pretty , isn't it?
}
Here you are cheking whether two box2D fixtures are in contact or not! And you can decide which fixtures you need to check for collision.
Sometimes unused textures may cause you memory leak! So you need to remove the unused textures.
For removing unused textures, use the following line of code, where ever you want to remove unused textures.
[[TextureMgr sharedTextureMgr] removeUnusedTextures];
Hi,
In certain situations you may need to remove all the forces you have applied on different bodies in your box2D world.
Then what to do?
Removing all the forces from the bodies in the box2D world is simple. Just use the single line of code.
yourWorld->ClearForces();
Here yourWorld is your Box2D world. Simple, isn’t it?
There may arise certain situations there you are using a number of @selector functions and want to stop all those selectors. In cocos2D there is an easy way to stop/unschedule all the selectors with a single line of code!
Use this line of code where ever you want to unshedule all the selectors being activated.
[self unscheduleAllSelectors];
CCBitmapFontAtlas faster than CCLabel.
Labels that update fast at the expense of more memory usage, like any other CCSprite,is the specialty of the CCBitmapFontAtlas class
//Usage...
CCBitmapFontAtlas scoreLabel = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"0"
fntFile:@"bitmapfont.fnt"];