今天总结一下触屏事件,做了主流飞行射击类游戏中玩家飞船随玩家的手指的移动改变位置的效果!
1.触屏事件的一般步骤
如果要使层监听到触屏事件(这里只总结单点触摸),这4个方法是必不可少的
- <span style="font-size:14px;">// default implements are used to call script callback if exist
- 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);</span>
在这些方法的实现中,处理触屏的各种事件
但是,还差了一步最重要的步骤----注册监听,这个可以写在层的init()方法中,但是为了取消监听,可以在onEnter()中注册监听,在onExit()中取消监听
- <span style="font-size:14px;">void GamePlayLayer::onEnter()
- {
- CCLayer::onEnter();
- CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);
- }
- void GamePlayLayer::onExit()
- {
- CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
- CCLayer::onExit();
- }</span>
- <span style="font-size:14px;">CCLayer::onEnter();
- </span>
- <span style="font-size:14px;">CCLayer::onExit();</span>
2.跟踪触摸点,实现飞船移动
(1)首先在ccTouchBegan()方法中记录触摸的起始点,并将触摸bool值设为true,为了保证从屏幕外开始触摸移动到屏幕上的触屏事件判断
- <span style="font-size:14px;">bool GamePlayLayer::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
- {
- mTouchPos = CCDirector::sharedDirector()->convertToGL(pTouch->locationInView());
- mIsTouching = true;
- return true;
- }</span>
(2)然后就是在ccTouchMoved()方法中根据当前点和起始点的差值,来确定飞船移动的位置
- <span style="font-size:14px;">void GamePlayLayer::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
- {
- if (mIsTouching) {
- CCPoint touchPos = CCDirector::sharedDirector()->convertToGL(pTouch->locationInView());
- CCPoint moveDelta = ccpSub(touchPos, mTouchPos);
- CCPoint nextPos = ccpAdd(mShip->getPosition(), moveDelta);
- if (CCRect::CCRectContainsPoint(winRect, nextPos)) {
- mShip->setPosition(nextPos);
- }
- mTouchPos = touchPos;
- }
- }</span>
(3)最后在ccTouchEnded()和ccTouchCancelled()中将触摸bool值设置回false
- <span style="font-size:14px;">void GamePlayLayer::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
- {
- mIsTouching = false;
- }
- void GamePlayLayer::ccTouchCancelled(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
- {
- mIsTouching = false;
- }</span>