user1526474
user1526474

Reputation: 945

Simple Animation in Cocoa Objective-C

I have written a simple animation for an iOS game and I am trying to convert it for Mac OS.

Here is my code for iOS

NSMutableArray *imgArr = [[[NSMutableArray alloc] init] autorelease];

    for(int i = 1; i < 6 + 1; i++) {
        [imgArr addObject: [UIImage imageNamed:[NSString stringWithFormat:@"%@%d.png", filePrefix, i]]];
    }

    UIImageView * animation = [[UIImageView alloc] initWithFrame:rect];
    animation.animationImages = imgArr;

    animation.animationRepeatCount = 1;
    [animation startAnimating];

    [self.view addSubview:animation];

As for cocoa, this part gives errors.. How can I fix this?

//animation.animationImages = imgArr;

//animation.animationRepeatCount = 1;
//[animation startAnimating];

New code with timer

for(int i = 0; i < 6; i++)
    [NSTimer scheduledTimerWithTimeInterval:1
                                     target:self
                                   selector:@selector(anim)
                                   userInfo:nil
                                    repeats:NO];


- (void)anim {
    ++num;


    NSImageView *animation = [[NSImageView alloc] initWithFrame:NSMakeRect(shipPosition.x, shipPosition.y, shipSize.width, shipSize.height)];

    [animation setImage: [NSImage imageNamed:[NSString stringWithFormat:@"explosprite%d.png", num]] ];
    [objectView addSubview:animation];

    [animation release];
}

Upvotes: 0

Views: 816

Answers (1)

Chuck
Chuck

Reputation: 237110

UIImageView does not exist in Cocoa at all. Cocoa does not really have support for sprite animation like you're trying to do here. The most common way AFAIK is just to set an NSTimer and update the image appropriately when the timer fires.

You could also create a custom CALayer subclass that handles animating images. I'm not sure that's necessarily easier, but it's an option.

Upvotes: 1

Related Questions