Three methods for adding gesture support in Cocos2d

Source: Internet
Author: User

Recently I have been pondering how to add the gesture function in Cocos2d. I have found some materials and my own understanding, and I have worked out three methods to share with you.

The first, very simple, is the Zhiyi cocos2d-iPhone tutorial-04 introduced (in fact this is not a real gesture, but can also achieve part of the gesture function), the Code is as follows:

1) Click and double-click

[Html]
-(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
// Click !!
Break;
Case 2: // Double tap.
// Double-click !!
Break ;}
}
Break;
}
}
}
2) gesture of separation and close of two fingers.

[Html]
// Calculate the distance function between two points
-(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 );
}
 
// Record the initial distance between multiple contacts
-(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 * toucher = [[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;
}
}
 
// When two fingers shift, determine whether to separate or collapse
-(Void) touchesMoved :( NSSet *) touches withEvent :( UIEvent *) event
{
NSSet * allTouches = [event allTouches];
Switch ([allTouches count])
{
Case 1:
Break;
Case 2 :{
UITouch * toucher = [[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"); // close !!
}
Else {
NSLog (@ "Zoom In"); // separate !!
}
}
Break;
}
}
Second, it is a method found in Cocoa China. Its principle is to implement gesture support by modifying the source code of the CCLayer and CCNode Cocos2d classes:

1. First, modify the source code of the two Cocos2d classes as CCLayer and CCNode.

2. added the gesture class source code CCGestureRecognizer.

The source code of the above three classes can be found in my resources (Address: http://download.csdn.net/detail/wangqiuyun/4460442), (remember CCLayer and CCNode to overwrite the original file)
CCGestureRecognizer. h and. m must be copied to the libs/cocos2d/Platforms/iOS directory of the current project.
Add CCGestureRecognizer. h and. m to the project file.

3. After completing the above work, all Node subclasses can use gestures, such as in the HelloWorld project:

1) modify the init method in HelloWorldLayer. m and add the following code:

[Html]
// Define the response gesture class (supports all UI gestures)
UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] init] autorelzer];
LongPress. minimumPressDuration = 0.5f;
LongPress. allowableMovement = 5.0f;
// Use longPress as the initialization parameter of the CCGestureRecognizer class.
// @ Selector (longPress: node :) is the trigger method of the response gesture.
CCGestureRecognizer * rescognizer = [CCGestureRecognizer CCRecognizerWithRecognizerTargetAction: longPress target: self action: @ selector (longPress: node :)];
// Set the proxy of the gesture class
Rescognizer. delegate = self;
// Register a gesture for self (currently CCLayer object)
[Self addGestureRecognizer: rescognizer];
// You must set self to receive Touch events.
Self. isTouchEnabled = YES;
2) You also need to add the implementation of the response method:

[Html]
-(Void) longPress :( UIGestureRecognizer *) recognizer node :( CCNode *) node
{
CCLOG (@ "% s" ,__ FUNCTION __);
}
3) The Protocol UIGestureRecognizerDelegate header file must be supported as follows:

[Html] view plaincopy
# Import "cocos2d. h"
 
// HelloWorldLayer
@ Interface HelloWorldLayer: CCLayer <UIGestureRecognizerDelegate>
{
}
 
// Returns a CCScene that contains the HelloWorldLayer as the only child
+ (CCScene *) scene;
-(Void) longPress :( UIGestureRecognizer *) recognizer node :( CCNode *) node;
@ End

Third, I think it's not bad for myself.

1) by default, the cocos2d template does not include a RootViewController attribute in AppDelegate. Therefore, you must manually add one:
Jump to the AppDelegate. h file and add the following code:
[Html]
@ Property (nonatomic, retain) RootViewController * viewController;

Then jump to AppDelegate. m, @ synthesize:
[Html]
@ Synthesize viewController;
2) In the scenario or layer m file, # import "AppDelegate. h"

[Html]
+ (Id) scene
{
// Add gesture support to the Layer
CCScene * scene = [CCScene node];

// 'Player' is an autorelisted object.
HelloWorld * layer = [HelloWorld node];

UIPanGestureRecognizer * gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget: layer action: @ selector (handlePanFrom :)] autorelzer];

AppDelegate * delegate = (AppDelegate *) [UIApplication sharedApplication]. delegate;
 
[Delegate. viewController. view addGestureRecognizer: gestureRecognizer];

// Add layer as a child to scene
[Scene addChild: layer];

// Return the scene
Return scene;
}
 
// Gesture recognition function
-(Void) handlePanFrom :( UIPanGestureRecognizer *) recognizer {

If (recognizer. state = UIGestureRecognizerStateBegan ){

CGPoint touchLocation = [recognizer locationInView: recognizer. view];
TouchLocation = [[CCDirector shareddire] convertToGL: touchLocation];
TouchLocation = [self convertToNodeSpace: touchLocation];
// Implementation results ..

} Else if (recognizer. state = UIGestureRecognizerStateChanged ){

CGPoint translation = [recognizer translationInView: recognizer. view];
Translation = ccp (translation. x,-translation. y );
// Implementation results ..
[Recognizer setTranslation: CGPointZero inView: recognizer. view];

} Else if (recognizer. state = UIGestureRecognizerStateEnded ){

// Implementation results ..

}
}
The above are three methods I have summarized to add gesture support in Cocos2d. If not, please kindly advise!


Author: wangqiuyun

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.