特别声明:本文所有图片资源来源于MoonWarriors cocos2d-html 开源项目
今天总结一下触屏事件,做了主流飞行射击类游戏中玩家飞船随玩家的手指的移动改变位置的效果!
1.触屏事件的一般步骤
如果要使层监听到触屏事件(这里只总结单点触摸),这4个方法是必不可少的
// 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);
在这些方法的实现中,处理触屏的各种事件
但是,还差了一步最重要的步骤----注册监听,这个可以写在层的init()方法中,但是为了取消监听,可以在onEnter()中注册监听,在onExit()中取消监听
void GamePlayLayer::onEnter()
{
CCLayer::onEnter();
CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);
}
void GamePlayLayer::onExit()
{
CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
CCLayer::onExit();
}
这里要特别注意的是一定要有父类方法的调用,不然这个层的加载就会有问题!
CCLayer::onEnter();
CCLayer::onExit();
2.跟踪触摸点,实现飞船移动
(1)首先在ccTouchBegan()方法中记录触摸的起始点,并将触摸bool值设为true,为了保证从屏幕外开始触摸移动到屏幕上的触屏事件判断
bool GamePlayLayer::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
mTouchPos = CCDirector::sharedDirector()->convertToGL(pTouch->locationInView());
mIsTouching = true;
return true;
}
(2)然后就是在ccTouchMoved()方法中根据当前点和起始点的差值,来确定飞船移动的位置
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;
}
}
(3)最后在ccTouchEnded()和ccTouchCancelled()中将触摸bool值设置回false
void GamePlayLayer::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
mIsTouching = false;
}
void GamePlayLayer::ccTouchCancelled(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
mIsTouching = false;
}