[Code Sharing] Detecting Key being held down

Hi people. I have 3 days with Coco2d and 3 days with games programming. The first problem I found while programming with cocos was that there was no event to detect a key being held down. Searching the forum and google I found a couple of solutions, well, not really, I found just one solution from “Game from Scratch”. It is a bit overcomplicated so I decided to share my solution, so the next time somebody have the same problem, they can use the searching tool and find this. I saw that the KeyCode was an enum, and every key corresponded to an integer number as in the Ascii code. That is why I created an array of 255 positions. If you see any problem feel free to reply and fix my code. Here it goes.

Declare an array as a private field in your class:

	boolean keys[255] = { false };

Implement some lambdas for the events, in the init method of your class, as follows:

	keyboardListener->onKeyPressed = [&](EventKeyboard::KeyCode code, Event* event) {
		keys[(int)code] = true;
	};
	keyboardListener->onKeyReleased = [&](EventKeyboard::KeyCode code, Event* e) {
			keys[(int)code] = false;
	};
	this->_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, pad);

Check for the keys you want to use, in the main loop:

void HelloWorld::update(float delta) {
	
	if (keys[(int)EventKeyboard::KeyCode::KEY_LEFT_ARROW]) {
		pad->setPosition(pad->getPosition().x - 1 * speed * delta, pad->getPosition().y);
	}

	if (keys[(int)EventKeyboard::KeyCode::KEY_RIGHT_ARROW]) {
		pad->setPosition(pad->getPosition().x + 1 * speed * delta, pad->getPosition().y);
	}

That’s it, cheers and till the next time

2 Likes

can i use this in our docs?

Yes ofcourse you can sir! feel free to use or modify it the way you want.

Well, this is quite a simple solution to implement yourself as to why there isn’t a built in one I guess. At least make the thing a map of cocos2d::EventKeyboard::KeyCode and bool so you can actualy look up what keys are pressed if you need to.

For reference (as this is “code-sharing”) I have a similar solution built inside my CCX library that you can just attach to any node and capture any keyboard events. You can find it in the input section.

Thank you, crugthew, yeah, there is nothing funcy with my code, i am not blaming cocos neither, its an awesome and powerfull framework. i didn’t wanted to make it with a map, because i wanted to keep it simple, very simple, since its going to be read by newcomers mostly, and at some point its quicker than a map, in my use case, O(1) Vs O(log n). But yeah, if i want to know if A && B are being pressed i just have to check 2 conditions in O(1) time, it works for multiple keys at the same time.

I will check your library, thank you again