知易Cocos2D-iPhone 游戏开发教程004-02

代码示例

我们通过以下的代码示例来展示触摸处理程序。

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;

}

} ...

如果您对本文感兴趣,可以到这里下载完整PDF示例源代码下载

你可能感兴趣的:(cocos2d)