A Sprite is a 2D graphic. A Sprite is a single Texture.
auto mySprite = Sprite::create("mysprite.png");
auto mySprite = Sprite::create();
auto frame = SpriteFrame::createWithTexture(texture, rect, offset);
auto mysprite = Sprite::createWithSpriteFrame(frame);
auto mysprite = Sprite::createWithSpriteFrameName("mysprite.png");
auto mySprite = Sprite::create("mysprite.png", Rect(0,0,40,40));
After creating a Sprite, there are a variety of functions that can be applied to it.
Given:
auto mySprite = Sprite::create("mysprite.png");
// increases X and Y size by 4.0 uniformly
mySprite->setScale(4.0);
// increases just X scale by 4.0
mySprite->setScaleX(4.0);
// increases just Y scale by 4.0
mySprite->setScaleY(4.0);
// bottom left
mySprite->setAnchorPoint(0, 0);
// middle
mySprite->setAnchorPoint(0.5, 0.5);
// top right
mySprite->setAnchorPoint(1, 1);
// adjusts the X and Y skew by 4.0 uniformly
mySprite->setSkew(4.0);
// adjusts the X skew by 4.0
mySprite->setSkewX(4.0);
// adjusts the Y skew by 4.0
mySprite->setSkewY(4.0);
A sprite sheet
a way to combine sprites into a single texture while reducing the overall size compared to loading each Sprite individually. Why does this matter? When loading a Sprite
each hardware platform has constraints of a minimum texture size that it will need to load. As you can imagine there is a lot of unused space and this increases memory consumption, draw times and lowers your games frame rate. Using a sprite sheet
allows all of your sprites to be condensed filing unused space. Now only the entire spritesheet must meet the hardwares constraints and can be loaded all at the same time. This means you will significantly reduce memory usage, reduce the time it takes OpenGL to draw your sprites and keep the frame rate of your game high.
Here is an example sprite sheet:
Load your sprite sheet into the SpriteFrameCache
, probably in AppDelegate:
auto spritecache = SpriteFrameCache::getInstance();
spritecache->addSpriteFramesWithFile("sprites.plist");
A few examples of working with a sprite sheet:
Creating a Sprite
from the SpriteFrameCache
auto mySprite = Sprite::createWithSpriteFrameName("mysprite.png");
Creating an Animation
from SpriteFrameCache
auto anim1 = Animation::create();
anim1->addSpriteFrameWithFile("enemystand.png");
anim1->addSpriteFrameWithFile("enemymove1.png");
anim1->addSpriteFrameWithFile("enemymove2.png");
anim1->addSpriteFrameWithFile("enemymove3.png");
anim1->addSpriteFrameWithFile("enemymove4.png");
anim1->addSpriteFrameWithFile("enemymove5.png");
anim1->addSpriteFrameWithFile("enemyjump.png");
auto animation = Animate::create(anim1);
animation->setDuration(0.2f);
sprite->runAction(RepeatForever::create(animation));