如果非布景层类和其子类想要使用触摸,那么应该继承相应的代理,
如test项目中TouchesTest文件夹中Paddle.h,其类为继承CCSprite
的类,不为布景层类,其使用了代理CCTargetedTouchDelegate
与布景层不同的是,注册和注销触摸代理需要在OnEnter()和OnExit()中进行
非布景层类和其子类使用触摸的步骤:
1.继承相应的代理,如test项目中TouchesTest文件夹中Paddle.h继承代理CCTargetedTouchDelegate
2.OnEnter()和OnExit()中注册和注销触摸代理
3.实现需要的方法,bool ccTouchBegan(CCTouch* touch, CCEvent *event)是必须实现的
例如test项目中TouchesTest文件夹中Paddle.h
virtual void onEnter();
virtual void onExit();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
void Paddle::onEnter()
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
CCSprite::onEnter();
}
void Paddle::onExit()
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->removeDelegate(this);
CCSprite::onExit();
}