Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocos2d - Mac: Check for keyboard events?

I am using Cocos2d, which is a framework for creating iPhone games. Recently they released Mac support, and I am making a simple game for Mac.

However, I am clueless about how to check when X key is pressed on the Mac's keyboard.

Objective-C

like image 651
Voldemort Avatar asked Dec 28 '10 06:12

Voldemort


2 Answers

You should do:

self.isKeyboardEnabled = YES;

You can then use to receive messages for key presses:

-(void) ccKeyUp:(NSEvent*)event;
-(void) ccKeyDown:(NSEvent*)event;

This should do it.

Refer here for more information:

http://www.cocos2d-iphone.org/forum/topic/11725

like image 77
David Higgins Avatar answered Nov 12 '22 13:11

David Higgins


Here is an example :

-(id) init
{
    if( (self=[super init])) 
    {
        .
        .
        .

        self.isKeyboardEnabled = YES ;

        .
        .
        .
    }
}

- (void) ccKeyDown : (NSEvent*) KeyDownEvent
{
    NSString *str_1 = [KeyDownEvent characters];
    unichar ch = [str_1 characterAtIndex:0];

    if ( ch == 97)                  // if 'a' Button Pressed Down
    {
        if ( canMoveRight == NO)
        {
            canMoveLeft = YES ;
        }

    }
    else if ( ch == 100 )           // if 'd' Button Pressed Down
    {
        if ( canMoveLeft == NO)
        {
            canMoveRight = YES ;
        }
    }
}

- (void) ccKeyUp : (NSEvent*) KeyDownEvent
{

    NSString *str_1 = [KeyDownEvent characters];
    unichar ch = [str_1 characterAtIndex:0];

    if ( ch == 97)                  // if 'a' Button Released
    {
        canMoveLeft = NO ;
    }
    else if ( ch == 100 )           // if 'd' Button Released
    {
        canMoveRight = NO ;
    }
}

PS : character code is based on their ASCII code .

like image 5
Ahmadhp Avatar answered Nov 12 '22 13:11

Ahmadhp