现在的移动设备都是可触摸设备,对于触屏操作也是最理所当然或者常见的,然而我们需要通过对触屏事件进行注册,然而事件的注册,只需要我们重写几个虚函数即可做到
函数声明如下:在我们需要进行触屏事件的Scene类当中进行
virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(CCTouch*touch,CCEvent*event);
virtual void ccTouchMoved(CCTouch*touch,CCEvent*event);
virtual void ccTouchEnded(CCTouch*touch,CCEvent*event);
virtual void ccTouchCancelled(CCTouch*touch,CCEvent*event);
// virtual void onEnter();
virtual void onExit();
bool containsTouchLocation(cocos2d::CCTouch *touch);
bool isControl;
我们可以这样认为
void CGameScene::registerWithTouchDispatcher() {
//注册触摸事件
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(
this, 0, true);
}
bool CGameScene::ccTouchBegan(CCTouch*touch, CCEvent*event) {
if (containsTouchLocation(touch)) {
isControl = true;
//CCMessageBox("we got !!", "dsad");
return true;
}
else
{
// CCMessageBox("we got nothing", "dsade1");
}
return false;
}
void CGameScene::ccTouchMoved(CCTouch*touch, CCEvent*event) {
if (isControl) {
CCPoint touchPoint=convertTouchToNodeSpace(touch);
m_hinstance->setPosition(touchPoint);
}
}
void CGameScene::ccTouchEnded(CCTouch*touch, CCEvent*event) {
isControl = false;
}
void CGameScene::ccTouchCancelled(CCTouch*touch, CCEvent*event) {
isControl = false;
}
/*
void CGameScene::onEnter()
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
setTouchEnabled(true);
}*/
void CGameScene::onExit()
{
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
bool CGameScene::containsTouchLocation(cocos2d::CCTouch *touch)
{
CCPoint touchPoint=convertTouchToNodeSpace(touch);
return m_hinstance->boundingBox().containsPoint(touchPoint);
}
通过上述代码便能进行触摸检测,同时使得目标跟着手进行移动。
这里我要说的有一点,onEnter和registerWithTouchDispatcher两个函数,onEnter函数则是进行自动注册。而我们通过手动调用registerWithTouchDispatcher函数进行手动注册,这两个函数的函数体是一样的,只是区别在于手动和自动。
另外一点则是,进行Sprite的触摸检测
CCPoint touchPoint=convertTouchToNodeSpace(touch);
return m_hinstance->boundingBox().containsPoint(touchPoint);
这样就可以进行触摸之后的检测了。