Arbitur
Arbitur

Reputation: 39081

cocos2d animation sprite

Hi I'm making a game for iphone and when the sprite moves I want it to change image between 3 images so it looks like it's running. I'm using cocos2d right now and I'm pretty new to cocos2d. I know how to do this with cocoa but that doesn't work with cocos2d.

So my question is how do I change the sprite image between 3, images and I want to loop it while I'm holding my finger on a position on the screen?

Thanks in advance.

Upvotes: 0

Views: 2523

Answers (2)

Anand
Anand

Reputation: 1129

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"animations/grossini.plist"];

CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"grossini_dance_01.png"];
sprite.position = ccp( 100, 100);

CCSpriteSheet *spritesheet = [CCSpriteSheet spriteSheetWithFile:@"animations/grossini.png"];
[spritesheet addChild:sprite];
[self addChild:spritesheet];

NSMutableArray *animFrames = [NSMutableArray array];
for(int i = 1; i < 15; i++) {

    CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"grossini_dance_%02d.png",i]];
    [animFrames addObject:frame];
}

CCAnimation *animation = [CCAnimation animationWithName:@"dance" frames:animFrames];
// 14 frames * 0.2sec = 2,8 seconds
[sprite runAction:[CCRepeatForever actionWithAction: [CCAnimate actionWithDuration:2.8f animation:animation restoreOriginalFrame:NO] ]];

Upvotes: 0

Jesse Black
Jesse Black

Reputation: 7976

This is a pretty loaded question for being new to cocos2d.

I would work on the infinite animation first. Get that working and then work on pausing, resuming, and flipping the animation.

You can set up the animation in the same method that you are adding the sprite.

NSMutableArray *animFrames = [NSMutableArray array];
    for(int i = 1; i <= 3; i++) {
        CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"Sprite-%d.png",i]];
        [animFrames addObject:frame];
    }
    CCAnimation *animation = [CCAnimation animationWithName:@"run" delay:0.1f frames:animFrames];
    [mySprite runAction:[CCRepeatForever actionWithAction: [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO]]];

If you are unfamiliar with sprite sheets, there are plenty of free resources for creating a sprite sheet and plist (TexturePacker has a nice interface)

If you have trouble getting this to work, Ray Wenderlich has good tutorials. If you get this far here are some pointers for pausing, resuming, and flipping the animation

For pausing or resuming

[mySprite pauseSchedulerAndActions];
[mySprite resumeSchedulerAndActions];

Flip the animation whenever the touch directions switches horizontal directions

mySprite.flipX = YES; 
mySprite.flipX = NO;

Upvotes: 1

Related Questions