这是关于类的继承关系,CCStandardTouchDelegate用于处理多点触摸;CCTargetedTouchDelegate用于处理单点触摸。
首先在要使用的类的.h文件中注册
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);//单点触摸事件
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); //系统中断通知需要取消触摸事件的时候调用此函数,一般用不到
virtual
void
registerWithTouchDispatcher
();//可以在获得导演类的分布触摸类。
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
第一个参数是代理对象,第二个参数是触摸的优先级,第三个是是否“吞噬“,设置为true,则底层的触摸事件触发不到。
virtual void ccTouchesBegan(CCSet * set,CCEvent * e);//多点触摸事件
virtual void ccTouchesMoved(CCSet * set,CCEvent * e);
virtual void ccTouchesEnded(CCSet * set,CCEvent * e);
virtual void ccTouchCancelled(CCSet * set,CCEvent * e);//系统中断通知需要取消触摸事件的时候调用此函数,一般用不到。
virtual void registerWithTouchDispatcher();同上。
在.cpp文件中要实现触摸事件,首先在onEnter()中设置启动setTouchEnable(true);如果注册了registerWithTouchDispatcher()事件,可以在里面
设置CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);否则需要在init函数中设置;
在类中实现单点触摸事件:
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint point=pTouch->getLocationInView();//可以获取开始点击的坐标
return true;
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint touchLocation = pTouch->locationInView();//可以获取每次移动的坐标
touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
streak->setPosition( touchLocation );
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint point=pTouch->getLocationInView();//获取结束的坐标
}
在类中实现多点点触摸事件:
bool HelloWorld:: ccTouchesBegan(CCSet * set,CCEvent * e);
{
CCSetIterator iter=set->begin();//获取系统分配的数字,begin为第一个end为最后一个
for(;iter!=set->end();iter++){
CCTouch * mytouch=(CCTouch *)(* iter);
CCPoint cp=mytouch->getLocation();
if(mytouch->getID()==0){//遍历每一个,接下来的用法和单点触摸一样
CCSprite * sp=(CCSprite * )this->getChildByTag(1);
sp->setPosition(cp);
}
if(mytouch->getID()==1){
CCSprite * sp=(CCSprite * )this->getChildByTag(2);
sp->setPosition(cp);
}
}
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
{
//用法和ccTouchesBegan一样,先拆分为一个
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
{
//用法和ccTouchesBegan一样,先拆分为一个
}
最后
void HelloWorld::onExit(){
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);//移除触屏任务
}
点击demo代码还有关于拖动效果代码。