2013-03-05 90 views
1

编辑:好吧,我通过简单地看着TouchesTest cocos2d-x样本找到了解决方案。唯一缺少的东西是测试触摸位置是否包含在精灵矩形中并声称触摸。因此,我能够用EDITcocos2d-x - ccTouchBegan如何工作?

的那一个

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; 
} 

END

我试图拦截我在现场增加了一个对象的特定触摸来代替我以前的代码。

添加两个对象的代码:

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坐标)覆盖了整个屏幕,并阻止我访问它下面的元素。

任何想法可能是什么原因?

+0

嘿,我有同样的问题,你有没有找到解决这个问题吗? 看到我的问题: http://stackoverflow.com/questions/18188095/created-many-ccsprits-but-when-triggering-cctouchbegan-gives-the-last-one-allway – user63898 2013-08-13 12:23:09

回答

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); 

这应该解决