最近一直在折騰如何在 Cocos2d 裡加入手勢功能,翻了些資料加上自己的理解,整理出幾種可行的路徑。本文先談最直接的一種。
這是最省事的方案,嚴格說並不是真正的手勢辨識(那需要 UIGestureRecognizer 或自寫的轨迹分析),但足以覆蓋單擊、雙擊與雙指開合這幾種常見互動。
在 touchesEnded:withEvent: 中,先看有幾根手指,再看 tapCount:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
switch ([allTouches count]) {
case 1:
{
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
switch ([touch tapCount]) {
case 1: // 單擊
break;
case 2: // 雙擊
break;
}
}
break;
}
}
記得在該層啟用觸摸:self.isTouchEnabled = YES;,否則回呼根本不會進來。
做法是先記錄兩指初始距離,再在移動時比對新距離。距離變小是合攏(zoom out),變大是分開(zoom in):
// 兩點距離
- (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: break;
case 2:
{
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];
CGFloat finalDistance = [self distanceBetweenTwoPoints:
[touch1 locationInView:[self view]]
toPoint:[touch2 locationInView:[self view]]];
if (initialDistance > finalDistance) {
NSLog(@"Zoom Out"); // 合攏
} else {
NSLog(@"Zoom In"); // 分開
}
}
break;
}
}
長處很明顯:不依賴任何額外 API,邏輯全在自己手裡,要加自訂手勢(例如「畫圈」、「三指平移」)反而比用現成 recognizer 自由。
限制也很實際:tapCount 只能分辨點擊次數,無法區分長按、掃動與拖曳;雙指縮放也只給了「方向」而沒有「比例」,真要拿來縮放精靈,還得自己把 finalDistance / initialDistance 乘到 scale 上,並在 touchesBegan 時重設基準值,否則會 continuously 累加而失控。另外別忘了在 touchesEnded 把 initialDistance 清掉,避免下一次單指操作沿用舊值。
若需要更完整的辨識能力(旋轉、三指以上、與系統手勢共存),後續文章會談另外兩種做法:一是把 UIGestureRecognizer 掛到 openGLView 上再把座標轉成 GL 空間,二是自己維護一份觸控軌跡樣本做比對。