Home > iPhone Development > Cocos2d Example – Move Sprite

Cocos2d Example – Move Sprite

Cocos2d engine significantly simplifies the process of iPhone game development. In this example, we will use an image of red square as the sprite. When we touch a position on the screen, the sprite will smoothly move to this position. Before starting this tutorial, we should first make sure the Cocos2d envirenment has been built up. In order to simplify this process, you can download Cocos2d 0.7.2 project template from here and install it at a proper location.

Step 1: Create a Cocos2d project. If you have properly installed the Cocos2d project template, you will see the option shown in the image below.
1

Select Cocos2d Application, and name the project “BoxMove”.

Step 2: Add this image to Resources Group.

Step 3: Define the class BoxLayer, which is a subclass of Layer. The codes are shown as follows:

//  BoxLayer.h
#import "cocos2d.h"
#import "Layer.h"
 
@interface BoxLayer : Layer {
	Sprite* boxSprite;
}
@end
//  BoxLayer.m
 
#import "BoxLayer.h"
 
@implementation BoxLayer
 
-(id)init{
	self = [super init];
	if(nil!=self){
		isTouchEnabled = YES;
		boxSprite = [Sprite spriteWithFile:@"box.png"];
		[boxSprite setPosition:CGPointMake(25, 25)];
		[self add:boxSprite];
	}
	return self;
}
 
- (BOOL) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
	UITouch *touch = [touches anyObject];
	CGPoint point = [touch locationInView: [touch view]];
	[boxSprite runAction:[MoveTo actionWithDuration:1 position:[[Director sharedDirector]convertCoordinate:point]]];
	return YES;
}
@end

In the init method of class BoxLayer, we created a Sprite object with image box.png and set its initial position. (Note: We defined a Sprite pointer boxSprite in the class BoxLayer, and it is initialized at the end of init method.) In addition, we implemented ccTouchesBegan:withEvent method, which means the layer will response the touch event. In this method, we first get the position of the touch. Then we use the runAction method of boxLayer to move the sprite to this position. It should be noted that the method convertCoordinate converts UIKit coordinate to Cocos2d coordinate (Note: The touch event uses UIKit coordinate, which is different from Cocos2d coordinate).

Step 4: The project template has created MyScene class by default. We need to make the following modifications:

//  MyScene.h
 
#import
#import "Scene.h"
#import "BoxLayer.h"
 
@interface MyScene : Scene {
	BoxLayer* boxLayer;
}
@property (nonatomic, retain) BoxLayer* boxLayer;
@end
//  MyScene.m
 
#import "MyScene.h"
 
@implementation MyScene
@synthesize boxLayer;
-(void)dealloc{
	[boxLayer release];
	[super release];
}
-(id)init{
	self = [super init];
	if(nil != self){
		BoxLayer* layer = [[BoxLayer alloc]init];
		self.boxLayer = layer;
		[layer release];
		[self add:boxLayer];
	}
	return self;
}
@end

In the codes above, we defined a BoxLayer pointer boxLayer in MyScene class, which is assigned in the init method. In the end, we add boxLayer to the scene.

Step 5: Build & Go. You will see the running result in the following image:

Categories: iPhone Development
  1. Sean Carmody
    June 2nd, 2009 at 17:00 | #1

    At build & Run I get an error on this file:

    // MyScene.m

    #import “MyScene.h”
    error: #import expects “FILENAME” or
    warning: “/” within comment

    There is also a deprecated warning for “add”.

  2. Sean Carmody
    June 2nd, 2009 at 17:08 | #2

    The above error can be resolved easily.

    In “MyScene.h” there is a blank import call:

    #import

    Just delete that is it will compile fine.

    Thanks

  3. Allan
    June 5th, 2009 at 11:27 | #3

    Thanks for posting this. :) It very helpful. I changed it a bit because I was getting alot of warnings.

    [code]

    @implementation BoxLayer
    -(id)init{
    self = [super init];
    if(nil!=self){
    isTouchEnabled = YES;
    boxSprite = [Sprite spriteWithFile: @"box.png"];
    boxSprite.position = ccp( 25, 25);
    [self addChild: boxSprite];
    }
    return self;
    }

    - (BOOL) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
    {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView: [touch view]];

    // Move Sprite from current location to point touched in 1 second.
    [boxSprite runAction:[MoveTo actionWithDuration:1 position:[[Director sharedDirector]convertCoordinate:point]]];

    return YES;
    }

    @end
    [/code]

    Thanks Again

  4. Tony
    June 14th, 2009 at 03:10 | #4

    Nice example, but I have some problem in my iPhone simulator, the color is different…
    the background color is blue instead of black as well as the block….
    What am I missing?
    Thanks a lot.

  5. Jimmy
    June 16th, 2009 at 13:17 | #5

    I’m getting these errors even if I copy and paste your code… What am I doing wrong?

    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m: In function ‘-[BoxLayer init]‘:
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:12: error: incompatible type for argument 1 of ‘setPosition:’
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m: In function ‘-[BoxLayer ccTouchesBegan:withEvent:]‘:
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: error: incompatible type for argument 2 of ‘actionWithDuration:position:’
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: warning: ‘Sprite’ may not respond to ‘-runAction:’
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: warning: (Messages without a matching method signature
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: warning: will be assumed to return ‘id’ and accept
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: warning: ‘…’ as arguments.)
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:12: error: incompatible type for argument 1 of ‘setPosition:’
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: error: incompatible type for argument 2 of ‘actionWithDuration:position:’
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: warning: ‘Sprite’ may not respond to ‘-runAction:’
    /Volumes/Storage/Dev/BoxDemo/iphone/BoxDemo/Classes/BoxLayer.m:22: warning: (Messages without a matching method signature

  1. May 27th, 2009 at 18:47 | #1
  2. June 11th, 2010 at 22:51 | #2