在上节课我们能够显示关卡选择界面了,但是点击按钮没有任何反应,
那么我们这篇文章将会介绍如何响应点击触摸等事件。
要使精灵能够相应触摸事件,我们必须将我们的类继承于CCSprite和CCTargetedTouchDelegate,
那么我们还需要实现CCTargetedTouchDelegate中的三个虚函数
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
再加一个枚举类型
typedef enum tagPaddleState
{
kPaddleStateGrabbed,
kPaddleStateUngrabbed
} PaddleState;
1.他来存储捕获的状态,那么声明的类如下所示:
typedef enum tagPaddleState { kPaddleStateGrabbed, kPaddleStateUngrabbed } PaddleState; class Paddle : public CCSprite, public CCTargetedTouchDelegate { CC_SYNTHESIZE(PaddleState, m_state, state); public: Paddle(); ~Paddle(); virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); };
不再捕获状态中。
bool Paddle::initWithTexture(CCTexture2D* pTexture) { if (CCSprite::initWithTexture(pTexture)) { m_state = kPaddleStateUngrabbed; } return true; }3.添加一个static Paddle* paddleWithTexture(CCTexture2D* pTexture);来加载纹理,并返回Paddle实例
Paddle* Paddle::paddleWithTexture(CCTexture2D* pTexture) { Paddle *pPaddle = new Paddle(); pPaddle->initWithTexture(pTexture); pPaddle->autorelease(); return pPaddle; }
4.然后设置一下ccTouchBegan函数,
如果在捕获状态中,那么就不用继续捕获输入,
如果不正在捕获状态中,触摸点也不在精灵中,则不继续捕获输入,
如果不在捕获状态中,但是触摸点在精灵上,就设置捕获状态为正在捕获,并继续捕获后面的输入。
bool Paddle::ccTouchBegan(CCTouch* touch, CCEvent* event) { if (m_state != kPaddleStateUngrabbed) return false; if (!containsTouchLocation(touch)) return false; m_state = kPaddleStateGrabbed; return true; }
CCRect Paddle::rect() { CCSize size = getTexture()->getContentSize(); return CCRectMake(-size.width / 2, -size.height / 2, size.width, size.height); } bool Paddle::containsTouchLocation(CCTouch* touch) { CCPoint ccp = convertTouchToNodeSpaceAR(touch); return rect().containsPoint(ccp); }
5.输入结束后,设置为未捕获状态:
void Paddle::ccTouchEnded(CCTouch* touch, CCEvent* event) { m_state = kPaddleStateUngrabbed; }6.最后添加一个两个方法:
virtual void onEnter();
virtual void onExit();
在onEnter()中把精灵层注册到触摸事件的分发器中,
然后在onExit()中把注册的精灵层移除
void Paddle::onEnter() { CCDirector *pDirector = CCDirector::sharedDirector(); pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, false); CCSprite::onEnter(); } void Paddle::onExit() { CCDirector *pDirector = CCDirector::sharedDirector(); pDirector->getTouchDispatcher()->removeDelegate(this); CCSprite::onExit(); }
本篇完整代码下载:
http://download.csdn.net/detail/yincheng01/6723731