[ad_1]
I began to develop a recreation in Cocos2d-x- and I had problem shifting my sprite by keyboard enter,I attempted a tutorial I discovered in rezghob weblog and however it doesn’t transfer, right here is my code :
......................
auto eventListener = EventListenerKeyboard::create();
eventListener->onKeyPressed = CC_CALLBACK_2(Level1::onKeyPressed , this);
eventListener->onKeyPressed = CC_CALLBACK_2(Level1::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener , this);
this->scheduleUpdate();
return true;
void Level1::onKeyPressed(EventKeyboard::KeyCode keyCode , Event *occasion)
{
if (keys.discover(keyCode) == keys.finish())
{
keys[keyCode] = std::chrono::system_clock::now();
}
CCLOG ("Number of Keys: " , keys.dimension() );
}
void Level1::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* occasion)
{
if (keys.discover(keyCode) != keys.finish())
{
std::chrono::length<double> elapsed_seconds = std::chrono::system_clock::now() - keys[keyCode];
CCLOG("Key code %d was down for %f s", int(keyCode), elapsed_seconds.depend() );
}
keys.erase(keyCode);
CCLOG("Number of Keys:%f " , keys.dimension() );
}
void Level1::replace(float delta)
{
float translate = 10.0 * delta;
if (keys.discover(EventKeyboard::KeyCode::KEY_LEFT_ARROW) != keys.finish())
{
X = X - translate;
}
else if(keys.discover(EventKeyboard::KeyCode::KEY_RIGHT_ARROW) != keys.finish())
{
X = X + translate;
}
else if(keys.discover(EventKeyboard::KeyCode::KEY_UP_ARROW) != keys.finish())
{
Y = Y + translate;
}
else if(keys.discover(EventKeyboard::KeyCode::KEY_DOWN_ARROW) != keys.finish())
{
Y = Y - translate;
}
auto _player = this->getChildByTag(1);
_player->setPosition(X, Y);
You changed Pressed perform with Released:
Use please
eventListener->onKeyReleased = …
[ad_2]