Search code examples
swiftcocos2d-iphoneccsprite

Change the image of a CCSprite programmatically using cocos2d v3.x in Swift


I know there a many questions regarding this topic but they are all very old and I can't find a resource explaining how to do it in cocos2d v3.x and in Swift. I have some PNGs in a folder in SpriteBuilder and I have made it a Smart Sprite Sheet but I don't know what to do from there. The other questions' answers made me believe this would work:

hero.setSpriteFrame("image.png")

I have tried it but there is no method called that.

Thanks


Solution

  • SWIFT CODE

    var hero = CCSprite.spriteWithImageNamed("hero.png") as CCSprite;
    var frame = CCSpriteFrame.frameWithImageNamed("ImageName.png") as CCSpriteFrame
    hero.spriteFrame = frame;
    

    Obj.C CODE

     #define SPRITE_CACHE ([CCSpriteFrameCache sharedSpriteFrameCache])
    
     carSprite.spriteFrame = [SPRITE_CACHE spriteFrameByName:@"redCar.png"]