cocos2dx 多点触屏事件

CCScene* HelloWorld::scene()

{

    // 'scene' is an autorelease object

    CCScene *scene = CCScene::create();

    

    // 'layer' is an autorelease object

    HelloWorld *layer = HelloWorld::create();



    // add layer as a child to scene

    scene->addChild(layer);



    // return the scene

    return scene;

}



// on "init" you need to initialize your instance

bool HelloWorld::init()

{

    //////////////////////////////

    // 1. super init first

    if ( !CCLayer::init() )

    {

        return false;

    }

    

//    开启多点触摸监听务必调用此函数

    setTouchEnabled(true);

    

    CCSprite * sp1 = CCSprite::create("Icon.png");

    sp1->setColor(ccc3(255, 255, 0));//便于区分

    sp1->setPosition(ccp(150,100));

    addChild(sp1, 0 , 91);

    

    CCSprite *sp2 = CCSprite::create("Icon.png");

    sp2->setPosition(ccp(150,200));

    addChild(sp2,0 , 92);

    return true;

}





//    重写多触摸点回调函数



//注册多触点的委托监听

 void HelloWorld:: registerWithTouchDispatcher(void)

{

    CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);

    

}

//用户手指第一次触摸

void HelloWorld:: ccTouchesBegan(CCSet * pTouches,CCEvent * pEvent)

{

    CCSetIterator iter = pTouches->begin();

    for (; iter!=pTouches->end(); iter++) {

        CCTouch * pTouch = (CCTouch * )(* iter);

        CCPoint location = pTouch->getLocation();

        if (pTouch->getID() == 0) {

//            第一个触点

            CCSprite * sp1 = (CCSprite* )this->getChildByTag(91);

            sp1->setPosition(location);

        }else if (pTouch->getID()==1){

            CCSprite * sp2 =  (CCSprite* )this->getChildByTag(92);

            sp2->setPosition(location);

        

        }

    }

}



//用户手指进行移动或者拖拽

void HelloWorld:: ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)

{

    CCSetIterator iter = pTouches->begin();

    for (; iter!=pTouches->end(); iter++) {

        CCTouch * pTouch = (CCTouch * )(* iter);

        CCPoint location = pTouch->getLocation();

        if (pTouch->getID() == 0) {

            //            第一个触点

            CCSprite * sp1 = (CCSprite* )this->getChildByTag(91);

            sp1->setPosition(location);

        }else if (pTouch->getID()==1){

            CCSprite * sp2 =  (CCSprite* )this->getChildByTag(92);

            sp2->setPosition(location);

            

        }

    }

}



//用户手指拾起

void HelloWorld:: ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)

{

     CCSetIterator iter = pTouches->begin();

    for (; iter!=pTouches->end(); iter++) {

        CCTouch * pTouch=(CCTouch * )(* iter);

        CCPoint loaction = pTouch->getLocation();

        CCLog("pTouch 触摸点%i坐标:x=%f , y=%f",pTouch->getID(),loaction.x ,loaction.y);

    }

}

//    生命周期函数

void HelloWorld:: onExit()

{

    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);

    CCLayer::onExit();

    

}

 

你可能感兴趣的:(cocos2dx)