首页 > 代码库 > cocos2dx-3.2 笔记 - 点击事件
cocos2dx-3.2 笔记 - 点击事件
点击事件检测
直接上代码
auto dispatcher = Director::getInstance()->getEventDispatcher();auto listener = EventListenerTouchOneByOne::create();listener->onTouchBegan = CC_CALLBACK_2(GameLayer::onTouchBegan, this);listener->onTouchMoved = CC_CALLBACK_2(GameLayer::onTouchMoved, this);listener->onTouchEnded = CC_CALLBACK_2(GameLayer::onTouchEnded, this);dispatcher->addEventListenerWithSceneGraphPriority(listener, this);bool GameLayer::onTouchBegan(Touch* touch, Event *event){ return true;}void GameLayer::onTouchMoved(Touch* touch, Event *event){}void GameLayer::onTouchEnded(Touch*touch, Event *event){}
检测点击了Sprite
bool GameLayer::CheckTouchAli(Touch *touch){ //将点击点转换成自己坐标系中的坐标,即相对于aliSprite(一个Sprite)的原点 Vec2 pt = aliSprite->convertTouchToNodeSpace(touch); int nw = aliSprite->GetRect().size.width; int nh = aliSprite->GetRect().size.height; Rect rc(0,0, nw, nh); return rc.containsPoint(pt);}
Sprite跟随拖动
void GameLayer::SetAliPosToTouchPos(Touch* touch){ Vec2 pt = aliSprite->convertTouchToNodeSpace(touch); int nw = aliSprite->GetRect().size.width; int nh = aliSprite->GetRect().size.height; Vec2 touchPos = Vec2(aliSprite->getPositionX()-nw*0.5+pt.x ,aliSprite->getPositionY()-nh*0.5+pt.y); aliSprite->setPosition(touchPos);}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。