最近一直琢磨在Cocos2d裡添加手勢的功能,找了一些資料加上自己的理解,整理出了三種方法和大家分享。
第一種,很簡單,就是知易cocos2d-iPhone教程-04所介紹的(其實這並不是真正的手勢,只是也能實現部分手勢功能而已),代碼如下:
1) 單擊、雙擊處理
- - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
- {
- //Get all the touches.
- NSSet *allTouches = [event allTouches];
- //Number of touches on the screen
- switch ([allTouches count])
- {
- case 1:
- {
- //Get the first touch.
- UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
- switch([touch tapCount])
- {
- case 1://Single tap
- // 單擊!!
- break;
- case 2://Double tap.
- // 雙擊!!
- break; }
- }
- break;
- }
- }
- }
2) 兩個指頭的分開、合攏手勢。
- //計算兩個點之間的距離函數
- - (CGFloat)distanceBetweenTwoPoints:(CGPoint)fromPoint toPoint:(CGPoint)toPoint
- {
- float x = toPoint.x - fromPoint.x;
- float y = toPoint.y - fromPoint.y;
- return sqrt(x * x + y * y);
- }
-
- //記錄多觸點之間的初始距離
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
- NSSet *allTouches = [event allTouches];
- switch ([allTouches count])
- {
- case 1: { //Single touch
- break;}
- case 2: { //Double Touch
- //Track the initial distance between two fingers.
- UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
- UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];
- initialDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:[self view]] toPoint:[touch2 locationInView:[self view]]];
- }
- break;
- default:
- break;
- }
- }
-
- //兩個指頭移劢時,判斷是分開還是合攏
- - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
- {
- NSSet *allTouches = [event allTouches];
- switch ([allTouches count])
- {
- case 1:
- break;
- case 2:{
- UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
- UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];
- //Calculate the distance between the two fingers.
- CGFloat finalDistance = [self distanceBetweenTwoPoints: [touch1 locationInView:[self view]] toPoint:[touch2 locationInView:[self view]]];
- //Check if zoom in or zoom out.
- if(initialDistance > finalDistance) {
- NSLog(@"Zoom Out"); // 合攏!!
- }
- else {
- NSLog(@"Zoom In"); // 分開!!
- }
- }
- break;
- }
- }