我在屏幕上有我的精灵,我有一个存储每个精灵的向量。
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 时,这个 sprite 处于打开状态,尽管我确实击中了实现 Layer 的类中的那些并将这些 sprites 放在图层上。
更新:我一直在尝试的代码:
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();
}