Extending "Sprite" class and create a new "Button" class from it?

Hi, I was using AndEngine (Java) and switched to Cocos2d-x and I loved it but I’m not too familiar with C++. So I don’t know this:

Can I have a “Button” subclass of Sprite class, I want to use this class to create button objects easily, for example look at this code:

public Button extends Sprite(String buttonText, int x, int y, Function touchFunction)
{
    ...
    Create sprite with "button.png" image,
    Attach buttonText Text object on top of the image,
    Set its position at (x,y),
    Set callback function which will be called when the button is touched.
    ...
}

Can I create a class like this and use it for all my buttons, for example like this:

Button button1 = new Button("New Game", 100, 100, startGame());
Button button2 = new Button("Options", 200, 200, openOptions());

Hope you understand me, I just want to customize the Sprite class to make it like a button…

You don’t need to implement it, because cocos2d-x already supports UI elements.
Have a look at the ui::Button class.

Sure. C++ even supports multiple inheritance, but that code is not valid C++.

Sure. Java is not that different from C++. You just have to implement a constructor in C++.

1 Like

Thanks for help, I want to use cocos2d::ui::Button class but it says there are only two classes of cocos2d::ui:: namespace (Widget and Scale9Sprite). So there is no Button class. I included cocos2d.h but it still doesnt accept button class. It just says this

Error: cocos2d::ui namespace has no member "Button"

thanks for help

Which engine version?

You have to include the master header: #include "ui/CocosGUI.h"

1 Like

thanks it worked with this: #include “ui/CocosGUI.h”