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

心不动则不痛 提交于 2020-01-06 06:48:33

问题


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.


回答1:


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.




回答2:


I do it like this:

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



回答3:


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.




回答4:


Try using

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



来源:https://stackoverflow.com/questions/1426308/how-to-change-the-image-in-a-cocos2d-sprite-from-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!