Feel free to fix/add documentation to the wiki

Hello Events

Valid for cocos2d v0.99.0 or newer

hello_events.jpg

Important: This example ONLY shows the basic steps to read the touch and accelerometer events. Some advanced options regarding the initialization were removed to simplify the sample.

Implementation File

File: HelloEvents.m

In objective-c the implementation is defined in the .m file, while the interfaces are defined in the .h file.

Import Headers

Like in c / c++ / java / etc, you need to import the needed headers.

// Needed for UIWindow, NSAutoReleasePool, and other objects
#import <UIKit/UIKit.h>
 
// Import the interfaces
#import "HelloEvents.h" //Fix here
 
// A simple define used a tag
enum {
	kTagSprite = 1,
};

Layer

The magic occurs in the class. We create a Layer that supports both touches and the accelerometer:

  • Touches: the sprite will be moved to the touched coordinates
  • Accelerometer: the sprite will face and scale according to the accelerometer
@implementation HelloEvents
 
// on "init" you need to initialize your instance
-(id) init
{
        // always call "super" init
        // Apple recommends to re-assign "self" with the "super" return value
        if( (self=[super init] )) {
 
                // isTouchEnabled is an property of Layer (the super class).
                // When it is YES, then the touches will be enabled
                self.isTouchEnabled = YES;
 
                // isAccelerometerEnabled is property of Layer (the super class).
                // When it is YES, then the accelerometer will be enabled
                self.isAccelerometerEnabled = YES;
 
                //
                // CCLabel
                //
 
                // create and initialize a CCLabel
                CCLabel* label = [CCLabel labelWithString:@"Hello Events" fontName:@"Marker Felt" fontSize:64];
 
                // ask director the the window size
                CGSize size = [[CCDirector sharedDirector] winSize];
 
                // position the label on the center of the screen
                // "ccp" is a helper macro that creates a point. It means: "CoCos Point"
                label.position =  ccp( size.width /2 , size.height/2 );
 
                // add the label as a child to this Layer
                [self addChild: label];
 
                //
                // Sprite
                //
 
                CCSprite *sprite = [CCSprite spriteWithFile:@"grossini.png"];
                sprite.position = ccp( 50, 50);
 
                // z is the z-order. Greater values means on top of lower values.
                // Default z value is 0. So the sprite will be on top of the label.
                // Add the sprite with a tag, so we can later 'get' the sprite by this tag
                [self addChild:sprite z:1 tag:kTagSprite];              
        }
        return self;
}
 
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
        // in case you have something to dealloc, do it in this method
        // in this particular example nothing needs to be released.
        // cocos2d will automatically release all the children (CCLabel)
 
        // don't forget to call "super dealloc"
        [super dealloc];
}

Touch Callback

This callback will be called because isTouchesEnabled is YES. Possible events:

  • ccTouchesBegan
  • ccTouchesMoved
  • ccTouchesEnded
  • cctouchesCancelled
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
        UITouch *touch = [touches anyObject];
 
        if( touch ) {
                CGPoint location = [touch locationInView: [touch view]];
 
                // IMPORTANT:
                // The touches are always in "portrait" coordinates. You need to convert them to your current orientation
                CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:location];
 
                CCNode *sprite = [self getChildByTag:kTagSprite];
 
                // we stop the all running actions
                [sprite stopAllActions];
 
                // and we run a new action
                [sprite runAction: [CCMoveTo actionWithDuration:1 position:convertedPoint]];
 
        }       
}

Accelerometer callback

This callback will be called because isAccelerometerEnabled is YES.

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{       
        CCNode *sprite = [self getChildByTag:kTagSprite];
 
        // Convert the coordinates to 'landscape' coords
        // since they are always in 'portrait' coordinates
        CGPoint converted = ccp( (float)-acceleration.y, (float)acceleration.x);        
 
        // update the rotation based on the z-rotation
        // the sprite will always be 'standing up'
        sprite.rotation = (float) CC_RADIANS_TO_DEGREES( atan2f( converted.x, converted.y) + M_PI );
 
        // update the scale based on the length of the acceleration
        // the higher the acceleration, the higher the scale factor
        sprite.scale = 0.5f + sqrtf( (converted.x * converted.x) + (converted.y * converted.y) );
}

Application Delegate

This class handles the initialization. Probably all your games will have a similar Application Delegate. For the moment it's not that important if you don't understand the following code.

@implementation AppController
 
// window is a property. @synthesize will create the accesors methods
@synthesize window;
 
// Application entry point
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
 
        // Try to use CADisplayLink director
        // if it fails (SDK < 3.1) use Threaded director
        if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] )
                [CCDirector setDirectorType:CCDirectorTypeDefault];
 
        // create an initilize the main UIWindow
        window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 
        // Enable Multiple Touches ? No
        [window setMultipleTouchEnabled:NO];
 
        // Attach cocos2d to the window
        [[CCDirector sharedDirector] attachInWindow:window];
 
        // before creating any layer, set the landscape mode
        [[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
 
        // Make the window visible
        [window makeKeyAndVisible];
 
        // Create and initialize parent and empty Scene
        CCScene *scene = [CCScene node];
 
        // Create and initialize our HelloEvents Layer
        CCLayer *layer = [HelloEvents node];
        // add our HelloEvents Layer as a child of the main scene
        [scene addChild:layer];
 
        // Run!
        [[CCDirector sharedDirector] runWithScene: scene];
}
 
- (void) dealloc
{
        [window release];
        [super dealloc];
}
@end

Main entry point

Main entry point. Like any c or c++ program, the main function is the entry point.

int main(int argc, char *argv[]) {
	// it is safe to leave these lines as they are.
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	UIApplicationMain(argc, argv, nil, @"AppController");
	[pool release];
	return 0;
}

Header file

File: HelloEvents.h

 
// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"
 
// Application Delegate class
@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate, UIApplicationDelegate>
{
	// main UIWindow
	// The OpenGL view will be a attached to this UIWindow
    UIWindow *window;
}
 
// Make the main UIWindow a property
@property (nonatomic, retain) UIWindow *window;
@end
 
// HelloEvents Layer
@interface HelloEvents : CCLayer
{
}
@end