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