Search code examples
c++ioscocos2d-x

Create a sprite from a class that inherits CCSprite


I have a Balloon class (see this) that inherits from CCSprite. I have given it properties like balloonSpeed and balloonStrength. I seem to be having problems in it, though.

What I want to do is that when I make an instance of the Balloon class, I want it to do the following:

  • Give it a texture (a PNG file of a balloon).
  • Set properties like balloonSpeed and balloonStrength.
  • Add actions to make it move and accept touch input.

When the object is touched, I want to:

  • Count if # of taps = balloonStrength. if so, destroy Balloon.

I have done a simpler version of this where a Balloon object is destroyed when it is touched. I want to apply OOP and custom classes here but I can't seem to get the right way of doing it.

Thanks in advance.


Solution

  • then the h file should looks like below:

    #include "cocos2d.h"
    using namespace cocos2d;
    
    class Balloon : public cocos2d::CCSprite, public CCTargetedTouchDelegate {
    public:
    float balloonSpeed;
    int balloonStrength;
    int numberOfTaps;
    virtual void onEnter();
    virtual void onExit();
    virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
    virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
    virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
    }; 
    

    and in your touch method:

    bool Balloon::ccTouchBegan(CCTouch* touch, CCEvent* event){
        CCPoint touchLocation = this->getParent()->convertTouchToNodeSpace(touch);
        if (CCRect::CCRectContainsPoint(this->boundingBox(), touchLocation)) {
            this->numberOfTaps++;
            if(this->balloonStrength == this->numberOfTaps){ 
                this->removeFromParentAndCleanup(true);
            }
        }
    
        return true;
    }
    

    you can use it after you add the blueBalloon as a child of a layer or node as below:

    blueBalloon->balloonSpeed = 2.0f;
    blueBalloon->numberOfTaps = 0;
    blueBalloon->balloonStrength = 5;