Custom cocos2d Action For Animating an AtlasSprite’s TextureRect

Sep 23, 2009   //   by Derek van Vliet   //   Development  //  1 Comment

While working on our coming-soon first iPhone game, we have been having a lot of success with cocos2d. One area in particular that we have been impressed with is the ability to run “Actions” on sprites, string them together in sequences and wrap them in modifiers such as ease-in, ease-out etc. This has made it easy to make our UI lively and animated as well as animate our game objects.

Recently we had a need to animate an AtlasSprite’s texture rect in order to pan around an atlas sprite. We ended up creating a custom cocos2d action to do this and we figured it would be a good thing to give back to the community.

This will allow you to transform an AtlasSprite’s texture rect’s origin and size over the length of a provided duration. You can also wrap this in a modifier action such as ease-in or repeater.

Here is the code

TransformTextureRect.h:

#import "cocos2d.h"
 
@interface TransformTextureRect : IntervalAction {
	CGRect fromRect;
	CGRect toRect;
}
+(id) actionWithDuration:(ccTime)d toRect:(CGRect)rect;
-(id) initWithDuration:(ccTime)d toRect:(CGRect)rect;
 
@end

TransformTextureRect.m:

#import "TransformTextureRect.h"
 
@implementation TransformTextureRect
+(id) actionWithDuration:(ccTime)d toRect:(CGRect)rect {
	return [[[self alloc] initWithDuration:d toRect:rect] autorelease];
}
 
-(id) initWithDuration:(ccTime)d toRect:(CGRect)rect {
	if ( (self=[super initWithDuration:d] ) )
		toRect = rect;
	return self;
}
 
-(id) copyWithZone: (NSZone*) zone
{
	Action *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] toRect: toRect];
	return copy;
}
 
-(void) start
{
	[super start];
	fromRect = [(AtlasSprite*)target textureRect];
}
 
-(void) update: (ccTime) t
{	
	[(AtlasSprite*)target setTextureRect:CGRectMake(fromRect.origin.x + (toRect.origin.x - fromRect.origin.x) * t,
													fromRect.origin.y + (toRect.origin.y - fromRect.origin.y) * t,
													fromRect.size.width + (toRect.size.width - fromRect.size.width) * t,
													fromRect.size.height + (toRect.size.height - fromRect.size.height) * t)];
}
 
@end

Example Usage

This transforms an AtlasSprite’s texture rect to the position (25,25) and with a width and height of 50 over the course of 1 second:

[sprite runAction:[TransformTextureRect actionWithDuration:1 toRect:CGRectMake(25,25,50,50)]];

This does something similar to the above example, only it eases in and out of the action as well.

[sprite runAction:[EaseExponentialInOut actionWithAction:[TransformTextureRect actionWithDuration:2 toRect:CGRectMake(480,0,480,320)]]];

1 Comment

  • This class saved my day. Nice piece of work. Thanks!

Leave a comment

Our Games

Latest Tweets