cocos2d-x - ccTouchBegan是如何工作的?

时间:2013-03-05 15:39:03

标签: touch cocos2d-x ccsprite

编辑:好的,我只是通过观看TouchesTest cocos2d-x样本找到了解决方案。唯一缺少的是测试触摸位置是否包含在sprite rect中并声明触摸。因此,我能够用那个代码替换我以前的代码

bool Artifact::claimTouch(CCTouch* pTouch)
{
    CCPoint touchLocation = pTouch->getLocation();
    CCRect boundingBox = this->boundingBox();

    return boundingBox.containsPoint(touchLocation);
}

bool Artifact::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    if (claimTouch(pTouch))
    {
        CCLog("id:%i", this->id);
        return true;
    }
    return false;
}

编辑结束

我试图截取我在场景中添加的对象的特定触摸。

添加两个对象的代码:

Artifact* artifact1 = new Artifact(1);
Artifact* artifact2 = new Artifact(2);
CCRect cropRect = CCRectZero;
cropRect.size = CCSize(50,50);
artifact1->initWithFile("rock_small.png", cropRect);
artifact1->setPosition(CCPoint(100, 100));
artifact2->initWithFile("grey_rock.jpg", cropRect);
artifact2->setPosition(CCPoint(300, 200));

这是我在模拟器上获得的内容

screenshot http://img62.imageshack.us/img62/3284/cctouchbeganissue.png

我的工件类的代码

//的.h

class Artifact : public CCSprite, public CCTargetedTouchDelegate
{
public:
    Artifact(int id) : id(id), pressed(false){};

    virtual void onEnter();
    virtual void onExit();

    bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
private:
    int id;
    bool pressed;
};

//。CPP

void Artifact::onEnter()
{
    CCSprite::onEnter();
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
}

void Artifact::onExit()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
    CCSprite::onExit();
}

bool Artifact::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    CCLog("id:%i", this->id);

    return true;
}

无论我点击屏幕上的哪一点(即使我没有点击两个方格中的一个),在第二个工件上调用ccTouchBegan(输出为" id:2")。它就像我在最后位置添加的CCSprite(即顶部z坐标)覆盖整个屏幕并阻止我访问它下面的元素。

知道可能是什么原因?

1 个答案:

答案 0 :(得分:1)

观看TouchesTest cocos2d-x样本

几个关键点

class Paddle : public CCSprite, public CCTargetedTouchDelegate
    virtual void onEnter();
    virtual void onExit();
    bool containsTouchLocation(CCTouch* touch);
    virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
    virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
    virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);

这应该解决问题