Cocos2d-x使用iPhone的多点触控实现双机游戏

        之前在网上看到的多点触控的实现都是规定了哪个对象必须是第一个触点,哪个必须是第二个触点,以此类推。。。。。。多点触控的触点有一个ID数组,多点触控的实现是为每一个触点指定控制对象,为了实现第一个触点可以是任意一个对象,第二个触点是除了第一个对象的其他任一个对象,可以通过计算距离来判断将触点分给哪个对象:
这里以两个触点举例:
        假设我们设计一个飞机游戏,可以同时控制两个飞机,这就用到多点触控:

setTouchEnabled(true);//开启多触点监听

//用户手指进行移动或者拖拽
void Game::ccTouchesMoved(CCSet *pTouches,CCEvent *pEvent)
{
   CCSetIterator iter = pTouches->begin();
   if(plane0IsExist)//多机模式,单机模式不涉及多点触控
   {
    for (;iter !=pTouches->end(); iter++)
   {
       //获取两个飞机对象
       CCSprite *sp2 =(CCSprite*)this->getChildByTag(tag_player0);
       CCSprite *sp1 =(CCSprite*)this->getChildByTag(tag_player);
       CCPointpoint1=sp1->getPosition();
       CCPointpoint2=sp2->getPosition();
       CCTouch *pTouch =(CCTouch*)(*iter);
       CCPoint location =pTouch->getLocation();
       //根据触点与两个飞机之间的距离判断触控情况
      //首先触点与飞机必须足够近,不然用户并没有触碰到飞机
      //触点应该给相对较近的那个飞机
       if(pTouch->getID()==0)
       {
          if (Distance(location, point1)<100.0){
             sp1->setPosition(location);
          }
          else if(Distance(location,point2)<100.0)
             sp2->setPosition(location);
       }
       else if(pTouch->getID()==1)
       {
          if (Distance(location, point2)<100.0){
             sp2->setPosition(location);
          }
          else if(Distance(location,point1)<100.0)
             sp1->setPosition(location);
       }
   }
   }else{// 单机模式
       CCSprite *sp1 =(CCSprite*)this->getChildByTag(tag_player);
       CCPointpoint1=sp1->getPosition();
       CCTouch *pTouch =(CCTouch*)(*iter);
       CCPoint location =pTouch->getLocation();
       if (Distance(point1,location)<=sp1->getContentSize().width){
          sp1->setPosition(location);
       }
   }
}

//删除多触点的委托监听
void Game::onExit()
{
   this->unscheduleUpdate();
   this->unscheduleAllSelectors();
   CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
   CCLayer::onExit();
}

工程源码:
SpaceWar-GitHub
Cocos2d-x自创双机游戏源码-任意对象(飞机)先后顺序多点触控的创意实现


你可能感兴趣的:(Cocos2d-x)