【问题标题】:How do i simply change a sprite's image in cocos2d?我如何简单地更改 cocos2d 中的精灵图像?
【发布时间】:2011-04-25 20:45:53
【问题描述】:

我试过了

[[CCTextureCache sharedTextureCache] addImage: @"still.png"];

但由于某种原因,我总是得到一个扭曲的图像。这很可能是因为我的图像分辨率不同,但对于这个应用程序,它们不能具有相同的分辨率。如何在不经历制作 spritesheet 或动画等复杂过程的情况下更改 sprite 的图像。

【问题讨论】:

    标签: xcode cocos2d-iphone


    【解决方案1】:
    urSprite = [CCSprite spriteWithFile:@"one.png"];
    urSprite.position = ccp(240,160);
    [自我 urSprite z:5 标签:1];
    
    // 改变同一个精灵的图像
    [urSprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"two.png"]];
    

    【讨论】:

    • 这个例子在 cocos2d v3.0 中仍然有效吗? xcode 说“未声明标识符 'CCTextureCache'”。
    【解决方案2】:

    这是更改精灵图像的最直接方法(如果您通过精灵表加载它),这绝对有效(我在游戏中一直使用它)。 mySprite 是精灵实例的名称:

    [mySprite setDisplayFrame:
    [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: @"sprite1.png"] ];

    【讨论】:

    • 这是使用机智动画时更好的解决方案。如果动画正在运行并且您想停止它,请使用它,只是不要忘记停止动画动作。
    【解决方案3】:

    您只需调用 sprite.texture 函数。

    示例

    在您的 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];
    

    然后将精灵的图片改为tex2:

    sprite.texture = tex2;
    

    很简单!

    希望这有帮助!

    【讨论】:

    • 是 sprite.texture = tex2 和 sprite setDisplayFrame:frameCache spriteFrameByName 一样
    • @OMGPOP 是的,我相信是的。不过,这样做的好处是您可以预加载纹理。这真的取决于您的需求。
    【解决方案4】:

    在 cocos2d v3 中,我能够通过...完成此操作

    [mySprite setSpriteFrame:[CCSpriteFrame frameWithImageNamed:@"two.png"]]
    

    ...但我不知道这是否会产生长期伤害我的副作用。 :)

    【讨论】:

      【解决方案5】:

      这个简单的一行可以完成你的任务。

      [sprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"slot.png"]];
      

      【讨论】:

      • 原帖有什么问题?你对此做了哪些改变? @Ankur
      • 突出显示了编码部分。要查看更改,请参阅this link
      【解决方案6】:

      我使用 cocos2d 3.0,这段代码对我有用:

       [_mySprite setTexture:[CCTexture textureWithFile:@"myFile.png"]];
      

      【讨论】:

        【解决方案7】:

        在 Cocos2d-x v3 中,可以使用my_sprite->setTexture(sprite_path);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多