Moving a sprite to a touched location in cocos2d

Learn how to move a sprite to the location you touch on you iphone.

Start a new project. I am going to name mine touchAndMove.

Add this or another sprite to your file.

In HelloWorldScene.h add a CCSprite like so.

@interface HelloWorld : CCLayer{
CCSprite * _sprite;
}

In HelloWorldScene.m make the init method look like this.

-(id) init
{
if( (self=[super init] )) {
_sprite = [CCSprite spriteWithFile:@"Eyesopened.jpg"];
_sprite.position= ccp(_sprite.contentSize.width/2,_sprite.contentSize.height/2);
[self addChild:_sprite];
}
return self;
}

Now we need to add this line right after the if statement.

self.isTouchEnabled = YES;

This enables touches.

Now before dealloc add this

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
[_sprite runAction:[CCMoveTo actionWithDuration:3 position:location]];
}

This method is called when a touch ends. We get the touch location and turn it into a point called location. Then we move the sprite to the location over 3 seconds.

And that is how you move a sprite by touch.

Download the code for moving a sprite to a touched location in cocos2d

Copy right Britney Lee Johnson August 2010.

This entry was posted in cocos2d. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>