1. 程式人生 > >cocos2d-x 多觸點監聽

cocos2d-x 多觸點監聽

eve size inline let shared blog pbo har strong

[cpp] view plaincopy
  1. //首先到cocos2d-x項目下的ios目錄下。找到AppController.mm文件,在函數 didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 中加入例如以下函數: [__glView setMultipleTouchEnabled:YES];
  2. bool HelloWorld::init()
  3. {
  4. if ( !CCLayer::init() )
  5. {
  6. return false;
  7. }
  8. //開啟多觸點監聽務必調用此函數
  9. setTouchEnabled(true);
  10. CCSprite* sp1 = CCSprite::create("Icon.png");
  11. sp1->setPosition(ccp(150, 200));
  12. addChild(sp1, 0, 23);
  13. CCSprite* sp2 = CCSprite::create("Icon.png");
  14. sp2->setColor(ccc3(0, 255, 0));
  15. sp2->setPosition(ccp(150, 100));
  16. addChild(sp2, 0, 24);
  17. return true;
  18. }
  19. //第一次碰觸
  20. void HelloWorld::ccTouchesBegan(cocos2d::CCSet *touches, cocos2d::CCEvent *event)
  21. {
  22. CCSetIterator inter = touches->begin();
  23. for(; inter != touches->end(); inter++)
  24. {
  25. CCTouch* touch = (CCTouch*)(*inter);
  26. CCPoint point = touch->getLocation();
  27. if(touch->getID() == 0) //第一個觸點
  28. {
  29. CCSprite* sp1 = (CCSprite*)getChildByTag(23);
  30. sp1->setPosition(point);
  31. }else if(touch->getID() == 1)//第二個觸點
  32. {
  33. CCSprite* sp2 = (CCSprite*)getChildByTag(24);
  34. sp2->setPosition(point);
  35. }
  36. }
  37. }
  38. //移動或拖拽
  39. void HelloWorld::ccTouchesMoved(cocos2d::CCSet *touches, cocos2d::CCEvent *event)
  40. {
  41. CCSetIterator inter = touches->begin();
  42. for(; inter != touches->end(); inter++)
  43. {
  44. CCTouch* touch = (CCTouch*) (*inter);
  45. CCPoint point = touch->getLocation();
  46. if(touch->getID() == 0)
  47. {
  48. CCSprite* sp1 = (CCSprite*)getChildByTag(23);
  49. sp1->setPosition(point);
  50. }else if(touch->getID() == 1)
  51. {
  52. CCSprite* sp2 = (CCSprite*)getChildByTag(24);
  53. sp2->setPosition(point);
  54. }
  55. }
  56. }
  57. //用戶手指擡起
  58. void HelloWorld::ccTouchesEnded(cocos2d::CCSet *touches, cocos2d::CCEvent *event)
  59. {
  60. }
  61. //多觸點的托付監聽註冊放在onEnter的生命函數中會造成程序異常退出。默認都寫在以下函數中。

  62. void HelloWorld::registerWithTouchDispatche()
  63. {
  64. CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);
  65. }
  66. //刪除多觸點的托付監聽
  67. void HelloWorld::onExit()
  68. {
  69. CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
  70. //這句務必要寫
  71. CCLayer::onExit();
  72. }

cocos2d-x 多觸點監聽