我有2个按钮(左和右)和一个包含所有55个图像的精灵表。我想知道,使用按钮来浏览每个精灵的最佳方法是什么?
E.G。 按左按钮,添加第一个精灵。按右键,删除第一个精灵,添加第二个精灵。等等,直到它到达最后一张图像。
这是精灵表
#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:pspriteSheet z:0];
}
return self;
}
- (void) dealloc
{
CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
_p = nil;
[CCSpriteFrameCache purgeSharedSpriteFrameCache];
[CCTextureCache purgeSharedTextureCache];
[super dealloc];
}
我应该继续添加并删除它们吗?
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;
}
}
这里是“按钮”方法的名称
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
[self buttons:touchLocation];
return TRUE;
}
答案 0 :(得分:0)
由于它使用spriteframe,您可以使用setDisplay frame:
CCSpriteFrame* frame = [[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:@"spr1.png"];
[mySprite setDisplayFrame:frame];
这样可以节省内存,而不是总是添加和删除..