无法在Cocos2d-x V 3.0中增加整数

时间:2014-05-28 20:05:06

标签: c++ cocos2d-x cocos2d-x-3.0

我需要增加一个整数。我在这里有这个代码:

Utils.h:

class Utils{
static HUD* hudLayer();
static Layer* layerWithTag(int tag);
};

Utils.cpp:

HUD* Utils::hudLayer(){
    return (HUD*)Utils::layerWithTag(TAG_HUD);
}
Layer* Utils::layerWithTag(int tag)
{
    Scene *sc = Director::getInstance()->getRunningScene();
    if (sc->getTag() == TAG_GAME_SCENE) {
        Layer *layer = (Layer *)sc->getChildByTag(tag);
        return layer;
    }
    return NULL;
}

HUD.h

class HUD : public Layer{

public:
    int score1;
    Label* scoreLabel1;
    virtual bool init();
    void didScore();
    CREATE_FUNC(HUD);
};

HUD.cpp:

bool HUD::init(){
    if(!Layer::init()){return false;}
    score1 = 0;


    scoreLabel1 = Label::createWithSystemFont(CCString::createWithFormat("Score : %d",score1)->getCString(), “Arial“, 64);
    scoreLabel1->setAnchorPoint(Point(0.0f, 1.0f));
    scoreLabel1->setPosition(Point(20, Utils::s().height-10));
    this->addChild(scoreLabel1);
    return true;
}
void HUD::didScore(){
    score1+=10; // Error HERE after coming from onTouchBegan (says parentis null)
    scoreLabel1->setString(CCString::createWithFormat("Score : %d",score1)->getCString());
}

现在我在GameScene.h中使用onTouchBegan方法:

bool GameScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
    Point location = touch->getLocationInView();
    location = Director::getInstance()->convertToGL(location);

    if(location.x < 300.0f){
        Utils::hudLayer()->didScore();
    }
    return true;
}

我在这里做错了什么? 我可以用相同的方式增加V 2.x中的整数,但不能在V 3.0中增加。为什么?

1 个答案:

答案 0 :(得分:0)

在cocos2d-x中,v3是一个新的事件监听器系统(触摸,加速器等),你需要创建用于获取触摸的监听器。在GameScene :: init中你应该添加类似的东西

auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowTouches(true);
listener1->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);

this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener1, this);

看看: http://www.cocos2d-x.org/wiki/EventDispatcher_Mechanism