Learning basic actions

Using this tutorial, I am going to describe following points.

  • Scheduling
    • Scheduling a method
    • Unscheduling a method
  • Actions
    • CCMoveTo
    • CCMoveBy
    • Reversing an action
    • Creating a sequence of actions using CCSequence
Basic Actions

Basic Actions

First place following code in your HelloWorldLayer.m file (Also, replace init method)

// on "init" you need to initialize your instance
-(id) init
	if( (self=[super init])) {
                label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64];
		CGSize size = [[CCDirector sharedDirector] winSize];
		label.position =  ccp( size.width /2 , size.height/2 );
		[self addChild: label];
                [self schedule:@selector(moveToBottom) interval:0.5];
	return self;

- (void)moveByBottom {
    CGSize size = [[CCDirector sharedDirector] winSize];
    id action = [CCMoveBy actionWithDuration:0.25 position:ccp(0, (label.contentSize.height/2-size.height/2))];
    id actionReve = [action reverse];
    [label runAction:[CCSequence actions:action,actionReve, nil]];

- (void)moveToBottom {
    CGSize size = [[CCDirector sharedDirector] winSize];
    id moveTo=[CCMoveTo actionWithDuration:0.25 position:ccp(size.width /2,label.contentSize.height/2)];
    id moveTo2=[CCMoveTo actionWithDuration:0.25 position:ccp(size.width /2,size.height-label.contentSize.height/2)];
    id seq = [CCSequence actions:moveTo,moveTo2, nil];
    [label runAction:seq];

- (void) dealloc {
	[super dealloc];

Init method will create a label & place it in the center of the screen of device. Init method will also schedule a method moveToBottom & which will be called after every 0.5 seconds. To unschedule a selector use following line of code.

[self unschedule:@selector(moveByBottom)];

MoveToBottom method

This method will create an animation in such a way that label will move to up & down in device’s screen.
First we have obtained the size of the window. Then we provided a location (bottom) where we want to move the label & similarly we also provided a location (up) in second moveTo action. We have created a sequence of two moveTo actions & Label will run this sequence after each time interval of 0.5 seconds.

MoveByBottom method

This method will create similar animation as mentioned above, but it will use CCMoveBy instead of CCMoveTo.
Here in CCMoveBy, we have to provide co-ordinate relative to the location of target object.

In CCMoveTo, we have to provide exact co-ordinate, where we want to move object in window.
In CCMoveBy, we have to provide relative co-ordinate based on current location of target object.

Video illustration

Grab the sample code.

Thanks & Regards,

Sagar Kothari.

Leave a Reply

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