叠加触摸就是说两个触摸层叠加一起, 点击上边的层,则下边也会被点中.这个问题困扰我有一个星期了,不过终于还是解决了,心情很通畅,写点笔记作参考.
void CtrolSprite::setTouchEnableds(bool var)
{
if ( m_bTouchEnabled == var ) return;
m_bTouchEnabled = var;
if ( var )
{
auto dispather = Director::getInstance()->getEventDispatcher();
lisner = EventListenerTouchOneByOne::create();
lisner->setSwallowTouches( true );
lisner->onTouchBegan = [&](cocos2d::Touch *pTouch, cocos2d::Event *pEvent)
{
if ( !m_bTouchEnabled ) return true;
if ( isTouchInside( pTouch ) )
{
m_bSelected = true;
setColor( Color3B(150, 150, 150) );
return true; //返回真则吞噬低于此优先级的触摸层
}
return false;
};
lisner->onTouchMoved = [&](cocos2d::Touch *pTouch, cocos2d::Event *pEvent)
{
if ( !m_bTouchEnabled || !m_bSelected ) return;
if ( !isTouchInside(pTouch) ) m_bSelected = false;
};
lisner->onTouchEnded = [&](cocos2d::Touch *pTouch, cocos2d::Event *pEvent)
{
setColor( Color3B(255, 255, 255) );
if ( !m_bTouchEnabled || !m_bSelected ) return;
if ( isTouchInside(pTouch) && isVisible() )
{
if ( m_pTarget && m_selector )
{
(m_pTarget->*m_selector)(this);
}
}
m_bSelected = false;
};
dispather->addEventListenerWithFixedPriority(lisner, m_iPriority); //设置优先级负数越高触摸越靠前, 如果设置固定优先级,那么必须手动移除. //dispather->addEventListenerWithSceneGraphPriority(lisner, this); //这个是最前边的层越优先触摸.
}else
{
auto dispather = Director::getInstance()->getEventDispatcher();
dispather->removeEventListener( lisner );
}
}
看看吧.就这么简单.搞清楚原理就行
Rect CtrolSprite::getRect()
{
float t_fX = getPositionX() - getContentSize().width * getAnchorPoint().x;
float t_fY = getPositionY() - getContentSize().height * getAnchorPoint().y;
float t_fW = getContentSize().width;
float t_fH = getContentSize().height;
Rect box = Rect(t_fX, t_fY, t_fW, t_fH);
box.origin = Vec2::ZERO;
return box;
}
不是很理解上边代码. 领悟中....