xcode 如何在 cocos2d 中简单地更改精灵的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5783076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i simply change a sprite's image in cocos2d?
提问by user663425
I've tried
我试过了
[[CCTextureCache sharedTextureCache] addImage: @"still.png"];
But I always end up with a distorted image for some reason. It's most likely because my images are not the same resolution, but for this app, they can't have the same res. How do I change the sprite's image without going through the complicated process of making a spritesheet or an animation or any of that.
但由于某种原因,我总是以扭曲的图像结束。这很可能是因为我的图像分辨率不同,但对于此应用程序,它们不能具有相同的分辨率。如何在不经历制作 spritesheet 或动画或任何此类的复杂过程的情况下更改 sprite 的图像。
回答by ShinuShajahan
urSprite = [CCSprite spriteWithFile:@"one.png"]; urSprite.position = ccp(240,160); [self urSprite z:5 tag:1]; // Changing the image of the same sprite [urSprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"two.png"]];
回答by Marin Todorov
This is the most straight forward way to change the image of a sprite(if you have it loaded trough a spritesheet) this definitely works (I use it all the time in my game). mySprite is the name of the sprite instance:
这是更改精灵图像的最直接的方法(如果您通过精灵表加载它)这绝对有效(我在游戏中一直使用它)。mySprite 是精灵实例的名称:
[mySprite setDisplayFrame:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: @"sprite1.png"] ];
[mySprite setDisplayFrame:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: @"sprite1.png"] ];
回答by tallen11
You would just call the sprite.texturefunction.
您只需调用sprite.texture函数即可。
Example
例子
In your init method:
在您的 init 方法中:
CCTexture2D *tex1 = [[CCTextureCache sharedTextureCache] addImage:@"still.png"];
CCTexture2D *tex2 = [[CCTextureCache sharedTextureCache] addImage:@"anotherImage.png"];
CCSprite *sprite = [CCSprite spriteWithTexture:tex1];
//position the sprite
[self addChild:sprite];
Then to change the image of the sprite to tex2:
然后将精灵的图像更改为 tex2:
sprite.texture = tex2;
Very simple!
很简单!
Hope this helped!
希望这有帮助!
回答by Todd Kerpelman
In cocos2d v3, I was able to accomplish this with...
在 cocos2d v3 中,我能够通过...
[mySprite setSpriteFrame:[CCSpriteFrame frameWithImageNamed:@"two.png"]]
...but I have no idea if this has side effects that will hurt me in the long run. :)
...但我不知道这是否有从长远来看会伤害我的副作用。:)
回答by TankorSmash
In Cocos2d-x v3, you can use my_sprite->setTexture(sprite_path);
在 Cocos2d-x v3 中,你可以使用 my_sprite->setTexture(sprite_path);
回答by GurPreet_Singh
This simple one line can do your task.
这条简单的一行可以完成您的任务。
[sprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"slot.png"]];
回答by ediheld
I use cocos2d 3.0 and this code works for me:
我使用 cocos2d 3.0,这段代码对我有用:
[_mySprite setTexture:[CCTexture textureWithFile:@"myFile.png"]];