Extend node or sprite for game object class?


#1

Hi All, I’m starting to abstract out my game from a single scene. Currently I have my Hero extend node and in an init method add the sprite to the node. It’s working well, but is there a better method for this? I’m about to create many extensions, and want to have an abstract “game object” base class to extend all enemies/players/powerups etc. from. Please let me know your thoughts, thanks!

This is how I setup my hero/player now

using namespace cocos2d;


class Player : public Node
{
    
public:
    Player();
    ~Player();
    
    static Player * node(void);
    
    virtual bool initWithWorld(b2World *world);
    void setJoystick(HSJoystick *joystick);
    float returnRotation();
    Point returnPosition();
private:
    
    HSJoystick *m_pJoystick;
    b2World *m_pWorld; // box2d world member Pointer
    b2Body *body;
    b2CircleShape m_ShapeDef;
    b2FixtureDef m_fixtureDef;
    
    Speed *action;
    virtual void update(float dt);
    
    void stayInBoundries();
    void createWalkingAnimation();
    
    Sprite *pPlayer;
    Sprite *pShadow;
    Animate *playerWalk;
    Animate *switchToBat;
    Animate *switchToTorch;
    
};

/// CPP
Player::Player()
{
    
}

Player::~Player()
{
    
}


Player * Player::node( void )
{
    Player * pRet = new Player();
    pRet->autorelease();
    return pRet;
}

bool Player::initWithWorld(b2World *world)
{
    bool bRet = false;
    do
    {
        
        // initialize
        
        pPlayer = Sprite::createWithSpriteFrameName("ZF-hero-01.png");
       
        CC_BREAK_IF(! pPlayer);
        
        Size size = Director::getInstance()->getWinSize();
        
         // Define Body
        b2BodyDef bodyDef;
        bodyDef.type = b2_dynamicBody;
        bodyDef.position.Set(size.width/2/PTM_RATIO, size.height/2/PTM_RATIO);
        bodyDef.userData = pPlayer;
        body = world->CreateBody(&bodyDef);
        
        // Define box shape for our dynamic body.
        m_ShapeDef.m_p.SetZero();
        m_ShapeDef.m_radius = 0.7f;
        
        // Define the dynamic body fixture.
        m_fixtureDef.shape = &m_ShapeDef;
        m_fixtureDef.density = 15.0f;
        m_fixtureDef.friction = 1.0f;
        m_fixtureDef.restitution = 0.01f;
        
        
        body->SetLinearDamping(0.8f);
        body->SetAngularDamping(1.0f);
        
        
        body->CreateFixture(&m_fixtureDef);
        body->SetBullet(true);
        
        createWalkingAnimation();
        
        action = Speed::create(RepeatForever::create(playerWalk),0.0f);
        pPlayer->runAction(action);
        pPlayer->setTag(kTagPlayerNode);
        this->addChild(pPlayer);
        
        scheduleUpdate();
        
        bRet=true;
        
    }while(0);
    
    return bRet;
}



#2

Hey , look into component pattern
check the link , someone implemented such pattern of “Game Components” in cocos2d-x
you can learn from the code to get the basic idea