Is it possible to use a spritesheet image for a button

I have a spritesheet with a bunch of images i need to use for buttons, but when i do

Sprite::createWithSpriteFrameName("playbtn.png");

it gives an error in button saying

No matching function for call to ‘create’

edit: I’M USING 4.0 AND XCODE
edit again: I’M USING THIS LIEN OF CODE FOR THE BUTTON:

auto menuplay = cocos2d::ui::Button::create("playBtn.png", "playBtn_big.png", "playBtn_small.png");

https://docs.cocos2d-x.org/api-ref/cplusplus/v3x/d3/d5c/classcocos2d_1_1_sprite.html

what does it mean?

it means you should check the constructors to see why yours’ isn’t working.

ok thanks for the help

it looks like you may be doing it correctly. Can you show us more code please?

auto img = Sprite::createWithSpriteFrameName("playBtn.png"); // Tries to load from the spritesheet
    auto menuplay = cocos2d::ui::Button::create(img, "button_green.png", "button_small.png");
    
    menuplay->addTouchEventListener([&](Ref* sender, cocos2d::ui::Widget::TouchEventType type){
            switch (type)
            {
                case ui::Widget::TouchEventType::BEGAN:  // I havent coded anything to do when the button is pressed yet
                    break;
                case ui::Widget::TouchEventType::ENDED:
                    break;
                default:
                    break;
            }
    });

There is no such create function in the cocos2d::ui::Button class. If you looked at the UIButton.h header file to find out what is available, you would see these:

    static Button* create();
    ...
    static Button* create(const std::string& normalImage,
                          const std::string& selectedImage = "",
                          const std::string& disableImage = "",
                          TextureResType texType = TextureResType::LOCAL);
    ...

If you want to use a sprite sheet for the button graphics, then it’s straightforward:

cocos2d::ui::Button::create("playBtn.png", "button_green.png", "button_small.png", TextureResType::PLIST);

All the images need to be in that sprite sheet. If you want to mix and match sprite sheet and individual graphics, you’ll have to inherit from the ui::Button class and add your own create methods.

I realise I may be pointing out the obvious here, but reading the documentation and taking a quick look at the interfaces to the code you’re using does help, a lot.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.