Cocos2D анимация - PullRequest
       8

Cocos2D анимация

1 голос
/ 28 октября 2010

Я пытаюсь создать анимацию в моем приложении, написанном на cocos2d. Я делаю это на этом уроке http://getsetgames.com/tag/ccanimation/ Все отлично работает. Но я пишу весь код в своем классе Engine. Также у меня есть класс для объекта, который я хотел бы оживить. И у меня есть специальный класс для создания объекта. Сейчас

пытаюсь дальше Файл, который должен иметь анимационную таблицу. // GiftSprite.h

#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "LevelScene.h";

@interface GiftSprite : CCSprite {
...
    CCSpriteSheet *giftSpriteSheet;
}
...
@property (assign, readwrite) CCSpriteSheet *giftSpriteSheet;
...


@end 

Файл с созданием GiftSprite и методом addGift

-(void) addGift: (ccTime) time {
gift.giftSpriteSheet = [CCSpriteSheet spriteSheetWithFile:@"redGift.png"];// In this place I try retain.
gift = [GiftSprite spriteWithTexture:gift.giftSpriteSheet.texture rect:CGRectMake(0,0,30,30)];
}

И файл, который создает анимацию, если какое-то событие ловится.

NSLog(@"%@", gift.giftSpriteSheet);// in this place I see NULL
            CCAnimation *fallingShowAnimation = [CCAnimation animationWithName:@"fallingInSnow" delay:0.5f];
            for(int x=0;x<6;x++){
                CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:gift.giftSpriteSheet.texture rect:CGRectMake(x*30,0,30,30) offset:ccp(0,0)];
                [fallingShowAnimation addFrame:frame];
            }
            CCAnimate *giftAnimate = [CCAnimate actionWithAnimation:fallingShowAnimation];
            [gift runAction:giftAnimate];

И когда я это сделаю. на моей анимации я просто вижу белый квадрат. Как я могу решить эту проблему

1 Ответ

0 голосов
/ 21 ноября 2010

У меня были те же проблемы, пока я не прочитал, что когда вы подкласс CCSprite, вы должны установить initWithTexture, а затем использовать его в своем пользовательском методе init. Мой немного отличается, потому что я не использую спрайт лист, вот как я сделал это с моим подклассом CCSprite:

Заголовок:

#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState state;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;

}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;

@end

.m файл:

#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect
{
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture
{
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (state == kButtonStateNotPressed) return NO;
    if (state == kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (state == kButtonStateNotPressed) return YES;
    if (state == kButtonStatePressed) return NO;
    return YES;
}

- (id)initWithTexture:(CCTexture2D *)aTexture
{
    if ((self = [super initWithTexture:aTexture]) ) {

        state = kButtonStateNotPressed;
    }

    return self;
}

- (void)onEnter
{
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
    [super onEnter];
}

- (void)onExit
{
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}   

- (BOOL)containsTouchLocation:(UITouch *)touch
{
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    if (state == kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;
    if (buttonStatus == kButtonStatusDisabled) return NO;

    state = kButtonStatePressed;
    [self setTexture:buttonLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if ([self containsTouchLocation:touch]) return;

    state = kButtonStateNotPressed;
    [self setTexture:buttonNormal];

}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
state = kButtonStateNotPressed;
    [self setTexture:buttonNormal];


}
@end

Тогда в моей основной программе init:

CCTexture2D *redButtonNormal = [[CCTextureCache sharedTextureCache] addImage:@"RedButtonNormal.png"];

spuButton *redButton = [spuButton spuButtonWithTexture:redButtonNormal];

[self addChild:redButton];

Вы бы сделали то же самое, но включили бы это и в свою анимацию. Это помогает? Я надеюсь, что это так. Удачного кодирования!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...