ben
ben

Reputation: 29777

How to change the image in a cocos2d sprite from an array?

I'm trying to change the image that a sprite from an array is displaying. Here is the code I'm using:

((Sprite *)[enemiesArray objectAtIndex:index]).image = baseImage;

I get the error message:

error: request for member 'image' in something not a structure or union

What am I doing wrong?

Thanks for reading.

Upvotes: 0

Views: 4274

Answers (4)

Valerii Iatsko
Valerii Iatsko

Reputation: 64

You'd better do it this way:

Somewhere in the init:

CCSpriteBatchNode *spritesheet = [CCSpriteBatchNode batchNodeWithFile:@"car_anim.png"];
[self addChild:spritesheet];

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"car_anim.plist"];

Somewhere in action:

[yourSprite setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"car_left.png"]];

*.plist and *.png could be done with Zwoptex.

Other solutions might break you animation when you are trying to change the texture while doing it.

Upvotes: 1

Rudi
Rudi

Reputation: 2460

I do it like this:

Texture2D *texture = [[Texture2D alloc] initWithImage:myUIImage]
[sprite setTexture: texture];

Upvotes: 1

Biranchi
Biranchi

Reputation: 16327

Try using

[((Sprite *)[enemiesArray objectAtIndex:index]) setImage:baseImage];

Upvotes: 0

Christian
Christian

Reputation: 713

I don't think that this is the way to do this. Rather than that you should call one of the init methods:

- (id) initWithCGImage:(CGImageRef)image;

- (id) initWithTexture:(Texture2D*) tex;

- (id) initWithFile:(NSString *) imageFile;

In my game i do this differently, i have a class for my object called 'Zed' which i also store in an array. It has a sprite as a field and if i want to change the image i swap the whole sprite and make sure i hide the old and show the new one.

Upvotes: 0

Related Questions