您的位置:首页 > 移动开发 > Cocos引擎

简单说明cocos2d的触摸事件中如何确定选中对象

2014-03-26 14:44 525 查看
bool Paddle::ccTouchBegan(CCTouch* touch, CCEvent* event)

{

if (m_state != kPaddleStateUngrabbed) return false;

if ( !containsTouchLocation(touch) ) return false;

m_state = kPaddleStateGrabbed;

return true;

}

bool Paddle::containsTouchLocation(CCTouch* touch)

{

return rect().containsPoint(convertTouchToNodeSpaceAR(touch));

}

CCRect Paddle::rect()

{

CCSize s = getTexture()->getContentSize();

return CCRectMake(-s.width / 2, -s.height / 2, s.width, s.height);

}

以上代码是cocos2d testCpp项目中的代码 , 简单的说明自己对他的理解 大牛请略过

我做了测试当我点击一个对象的时候 cocos2d底层会把所有的在eventDispather注册的监听事件一个一个往上抛,(本人之前是学as的 所有会用as语言来做对比) 他不象as给确定对象发送回调函数

touch中有一个属性 点 他是根据你点击对象的锚点进行计算的 所以我们只要判断这个点是否在这个范围之内 就可以确定这个点击事件是否发上在点击的对象上

(里面很多细节 太懒 不想说)

以下是我自己做的一个实例

CCRect CardsComponent::rect()

{

CCSize s = m_cards->getTexture()->getContentSize();

return CCRectMake(-s.width / 2, -s.height / 2, s.width, s.height);

}

bool CardsComponent::containsTouchLocation(CCTouch* touch)

{

return rect().containsPoint(convertTouchToNodeSpaceAR(touch));

}

//触控点击

bool CardsComponent::onTouchBegan(Touch* touch, Event* event)

{

if (m_fightStat == Define::CARD_WAIT) //这张牌是否可以用

{

return false;

}

if (!containsTouchLocation(touch)) return false;

CCLog("mouse Down");

m_choiceStat = Define::CARD_SELECT;

return true;

}

void CardsComponent::onTouchEnded(Touch* touch, Event* event)

{

CCLog("mouse Up");

if (m_choiceStat == Define::CARD_SELECT)

{

//Point touchPoint = touch->getLocation();

m_choiceStat = Define::CARD_NOSELECT;

//判断条件 是否放置在战斗场景上

CCNotificationCenter::sharedNotificationCenter()->postNotification(NotificationName::CARD_CHOICE_FIGHT, this);

setPosition(ccp(m_startPoint.x, m_startPoint.y));

}

}

void CardsComponent::onTouchMoved(Touch* touch, Event* event)

{

Point touchPoint = touch->getLocation();

if (m_choiceStat == Define::CARD_SELECT)

{

Point point = ccp(touchPoint.x, touchPoint.y);

setPosition(point);

//takeInGuildLocal(touchPoint.y);

CCNotificationCenter::sharedNotificationCenter()->postNotification(NotificationName::CARD_LOCAL_NOW, touch);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐