歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Cocos2d中添加手勢支持的三種方法

Cocos2d中添加手勢支持的三種方法

日期:2017/3/1 10:13:16   编辑:Linux編程

最近一直琢磨在Cocos2d裡添加手勢的功能,找了一些資料加上自己的理解,整理出了三種方法和大家分享。

第一種,很簡單,就是知易cocos2d-iPhone教程-04所介紹的(其實這並不是真正的手勢,只是也能實現部分手勢功能而已),代碼如下:

1) 單擊、雙擊處理

  1. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  2. {
  3. //Get all the touches.
  4. NSSet *allTouches = [event allTouches];
  5. //Number of touches on the screen
  6. switch ([allTouches count])
  7. {
  8. case 1:
  9. {
  10. //Get the first touch.
  11. UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
  12. switch([touch tapCount])
  13. {
  14. case 1://Single tap
  15. // 單擊!!
  16. break;
  17. case 2://Double tap.
  18. // 雙擊!!
  19. break; }
  20. }
  21. break;
  22. }
  23. }
  24. }

2) 兩個指頭的分開、合攏手勢。

  1. //計算兩個點之間的距離函數
  2. - (CGFloat)distanceBetweenTwoPoints:(CGPoint)fromPoint toPoint:(CGPoint)toPoint
  3. {
  4. float x = toPoint.x - fromPoint.x;
  5. float y = toPoint.y - fromPoint.y;
  6. return sqrt(x * x + y * y);
  7. }
  8. //記錄多觸點之間的初始距離
  9. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  10. {
  11. NSSet *allTouches = [event allTouches];
  12. switch ([allTouches count])
  13. {
  14. case 1: { //Single touch
  15. break;}
  16. case 2: { //Double Touch
  17. //Track the initial distance between two fingers.
  18. UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
  19. UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];
  20. initialDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:[self view]] toPoint:[touch2 locationInView:[self view]]];
  21. }
  22. break;
  23. default:
  24. break;
  25. }
  26. }
  27. //兩個指頭移劢時,判斷是分開還是合攏
  28. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  29. {
  30. NSSet *allTouches = [event allTouches];
  31. switch ([allTouches count])
  32. {
  33. case 1:
  34. break;
  35. case 2:{
  36. UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
  37. UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];
  38. //Calculate the distance between the two fingers.
  39. CGFloat finalDistance = [self distanceBetweenTwoPoints: [touch1 locationInView:[self view]] toPoint:[touch2 locationInView:[self view]]];
  40. //Check if zoom in or zoom out.
  41. if(initialDistance > finalDistance) {
  42. NSLog(@"Zoom Out"); // 合攏!!
  43. }
  44. else {
  45. NSLog(@"Zoom In"); // 分開!!
  46. }
  47. }
  48. break;
  49. }
  50. }
Copyright © Linux教程網 All Rights Reserved