cocos2dbeginner
cocos2dbeginner

Reputation: 2207

How to get the status of some keys on the keyboard on the mac?

I'm using cocos2d for mac (1.0.1)

I have these two methods (which are similar to the apple ones)

//keyboard delegate is defined - these methods are called
- (BOOL)ccKeyDown:(NSEvent *)event {
    unichar key = [[event characters] characterAtIndex:0];
    if (key == NSDownArrowFunctionKey) {
        // Down arrow pressed
    }
    if(key == NSUpArrowFunctionKey) {
        // Up arrow pressed
        return YES;
    }
    if(key == NSLeftArrowFunctionKey) {
        // Left arrow pressed
       something = -1.0f;
        return YES;

    } else if(key == NSRightArrowFunctionKey) {
        // Right arrow pressed
       something = 1.0f;
        return YES;
    } 
    return NO;
}
-(BOOL)ccKeyUp:(NSEvent *)event {
    unichar key = [[event characters] characterAtIndex:0];
    if (key == NSDownArrowFunctionKey) {
        // Down arrow pressed
    }
    if(key == NSUpArrowFunctionKey) {
        // Up arrow pressed
    }
    if(key == NSLeftArrowFunctionKey || key == NSRightArrowFunctionKey) {
        // Left arrow pressed
       something = 0.0f;
    } 

    return YES;
}

I want to call this:

something = 0.0f;

if the left arrow key and the right arrow key are not pressed/hold. As far as I know ccKeyUp will only be called if a key was pressed and than released. And ccKeyDown if a key was pressed.

How can I get the current keyboard state to check a few keys for their states?

Upvotes: 1

Views: 1163

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

Cocos2D does not offer a way to just check the states of keyboard keys.

Kobold2D does. With Kobold2D you can do something like this:

KKInput* input = [KKInput sharedInput];
if ([input isKeyDown:KKKeyCode_LeftArrow] == NO && 
    [input isKeyDown:KKKeyCode_RightArrow] == NO)
{
    something = 0.0f;
}

Also, just as a side note, it is bad practice to use the characters for keyboard events:

unichar key = [[event characters] characterAtIndex:0];

The problem with that is that the user's locale (keyboard input language) changes which key or key combination needs to be pressed to generate that character. For example while the / (slash) key is conveniently located on US Keyboards to the left of the Right Shift key, on german keyboards the users would have to press Shift+7 to execute the action that you've mapped to the / character. You can learn more about this in my article about Correctly Processing Mac Keyboard Events.

Upvotes: 2

Related Questions