我有我的精靈在屏幕上,我有一個存儲每個精靈的向量。Cocos2d-x和處理觸摸事件
CCSprite *可以處理觸摸事件嗎?或者只是CCLayer *?
什麼是決定哪個精靈被觸動的最佳方法?我是否應該存儲精靈所在的座標(在精靈類中)以及何時得到事件,通過查看矢量並獲取每個精靈當前座標來查看用戶觸摸的位置是精靈的位置? 更新:我繼承CCSprite:
class Field : public cocos2d::CCSprite, public cocos2d::CCTargetedTouchDelegate
,我實現的功能:
cocos2d::CCRect rect();
virtual void onEnter();
virtual void onExit();
bool containsTouchLocation(cocos2d::CCTouch* touch);
virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchMoved(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchEnded(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void touchDelegateRetain();
virtual void touchDelegateRelease();
我把CCLOG聲明中每一個和我不打他們!
當我觸摸CCLayer時,雖然我在類中實現了圖層並將這些圖形放置在圖層上,但這個圖元仍然打開。
更新:我一直在試圖代碼:
Field* Field::createWithLocation(cocos2d::CCPoint p)
{
Field* f = new Field();
f->autorelease();
f->initWithLocation(p);
return f;
}
void Field::initWithLocation(cocos2d::CCPoint p)
{
setFieldCenterPoint(p);
setFieldGraphicName(FIELD::fieldIconFileName);
setFieldSprite(cocos2d::CCSprite::create(getFieldGraphicName().c_str()));
getFieldSprite()->setPosition(ccp(getFieldCenterPoint().x, getFieldCenterPoint().y));
setFieldSize(getFieldSprite()->getContentSize());
}
cocos2d::CCRect Field::rect()
{
cocos2d::CCSize s = getFieldSprite()->getTexture()->getContentSize();
return cocos2d::CCRectMake(-s.width/2, -s.height/2, s.width, s.height);
}
void Field::onEnter()
{
CCLOG("In onEnter");
cocos2d::CCDirector* pDirector = cocos2d::CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
//_dir->Instance()->getDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
cocos2d::CCSprite::onEnter();
}
void Field::onExit()
{
CCLOG("In onExit");
cocos2d::CCDirector* pDirector = cocos2d::CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->removeDelegate(this);
//_dir->Instance()->getDirector()->getTouchDispatcher()->removeDelegate(this);
cocos2d::CCSprite::onExit();
}
bool Field::containsTouchLocation(cocos2d::CCTouch* touch)
{
return rect().containsPoint(convertTouchToNodeSpaceAR(touch));
}
bool Field::ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event)
{
CCLOG("In ccTouchBegan");
return true;
}
void Field::ccTouchMoved(cocos2d::CCTouch* touch, cocos2d::CCEvent* event)
{
CCLOG("In ccTouchMoved");
}
void Field::ccTouchEnded(cocos2d::CCTouch* touch, cocos2d::CCEvent* event)
{
CCLOG("In ccTouchEnded");
}
void Field::touchDelegateRetain()
{
this->retain();
}
void Field::touchDelegateRelease()
{
this->release();
}
@ m.ding,我已經嘗試了您提供的鏈接中提到的解決方案,但在我的情況下它沒有用。 –
@ Rv15 - 你在分類什麼? – Jason