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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值