Change Sprite with Buttons - Cocos2d
I have 2 buttons (left and right) and a sprite sheet that contains all 55 images. I was wondering, what is the best way to go through each sprite using the buttons?
E.G. Press the left button and the first sprite is added. Press the right button, the first sprite is removed and the second sprite to added. So on and so forth until it reaches the last image.
This is the Sprite Sheet
#import "cocos2d.h"
@interface GameScene : CCLayer {
CCSpriteBatchNode *pspriteSheet
}
+(CCScene *) scene;
@property (nonatomic, retain) CCSprite *p;
@end
----------------------------------------------------
#import "GameScene.h"
@implementation GameScene
@synthesize p = _p;
+(CCScene *) scene
{
CCScene *scene = [CCScene node];
GameScene *layer = [GameScene node];
[scene addChild: layer];
return scene;
}
-(id) init
{
if ((self = [super init]))
{
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
@"PAnim.plist"];
pspriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"PAnim.pvr.ccz"];
[self addChild:pspriteShee开发者_StackOverflow社区t z:0];
}
return self;
}
- (void) dealloc
{
CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
_p = nil;
[CCSpriteFrameCache purgeSharedSpriteFrameCache];
[CCTextureCache purgeSharedTextureCache];
[super dealloc];
}
Should I just keep adding them and removing them?
E.G.
-(void)buttons:(CGPoint)touchLocation
{
if (CGRectContainsPoint(leftB.boundingBox, touchLocation) && tapP == YES && paused == NO) {
if (count == 1)
{
_p = [CCSprite spriteWithSpriteFrameName:@"p1.png"];
[pspriteSheet addChild:_p];
count = 2;
_p.position = ccp(240, 215);
}
if (CGRectContainsPoint(rightB.boundingBox, touchLocation) && tapP == YES && paused == NO) {
if (count == 2)
{
[pspriteSheet removeChild:_p cleanup:YES];
_p = [CCSprite spriteWithSpriteFrameName:@"p2.png"];
_p.position = ccp(240, 215);
[pspriteSheet addChild:_p];
count = 3;
}
}
Here is where the "buttons" method is called
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
[self buttons:touchLocation];
return TRUE;
}
Since it is using spriteframe, you can use setDisplay frame:
CCSpriteFrame* frame = [[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:@"spr1.png"];
[mySprite setDisplayFrame:frame];
This would save up memory instead of always adding and removing..
精彩评论