//To create a sprite from a file (png, jpg): CCSprite *mySprite = [CCSprite spriteWithFile:@"mySprite.png"]; //make sure you have imported the image file to your resources folder. //To set it's position on your scene: mySprite.position = ccp(240,180); // that position would be the center of an iPhone/iPod screen //To add it to the scene: [self addChild: mySprite];
// The sprite will have the size of the image CCSprite *mySprite = [CCSprite spriteWithFile:@"mySprite.png"];
// The sprite will have the size of the image CCSprite *mySprite = [CCSprite spriteWithFile:@"spritesheet.png" rect:CGRectMake(0,0,100,100)];
// A CCSpriteFrame object has a reference to the texture and texture rect. CCSpriteFrame *spiteFrame = [CCSpriteFrame frameWithTexture:texture rect:rect]; CCSprite *mySprite = [CCSprite spriteWithSpriteFrame:spriteFrame]; // You can also create an sprite using a CCSpriteFrame by name. // These frames can be loaded using the CCSpriteFrameCache CCSprite *mySprite = [CCSprite spriteWithSpriteFrameName:@"sprite_frame_name"];
An spritesheet, is a collection of sprites that are packed together in one big file.
The more sprites that are packed into the spritesheet the less texture memory it will consume.
There are 3 ways to create spritesheets for cocos2d:
These spritesheets don't have a metadata. They require that all the sprites have the same size, otherwise it will be impossible to know the location of each sprite.
These kind of spritesheets are not optimized. They contain a lot of “free” (wasted) space, and since the memory is a very precious resource on iOS, this is not the recommended way to create spritesheets.
Tools:
mkatlas.pl is an script shipped within cocos2d that lets you create sprite rects.
This tool also tries to optimize the unused space and packs the sprites in a way that there is no “wasted” space.
This tool generates the metadata in a .h header file.
This kind of spritesheet have, like mkatlas.pl optimizes the “wasted” space by sorting and/or rotating the sprites in order to maximize the spritesheet space.
It creates metadata file (a .plist file), that contains the position of the sprites, and the name of the sprites.
This is the recommended way to create spritesheets.
Available tools:
The CCSpriteFrameCache object can load these kind of spritesheets.
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"spritesheet.plist"];
If you want to create a CCSprite subclass, you need to implement ''initWithTexture:rect:' method.
Example:
@implementation MySprite -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect { if( (self=[super initWithTexture:texture rect:rect])) { ivar1 = xxx; ivar2 = yyy; ivar3 = zzz; } return self; } @end // And to create an instance of MySprite you simply do: MySprite *sprite = [MySprite spriteWithFile...]; // or any of the supported CCSprite methods.