Wednesday, October 12, 2022
HomeGame DevelopmentTransfer a sprite with Keyboard enter - C++

Transfer a sprite with Keyboard enter – C++


I began to develop a sport in Cocos2d-x- and I had problem shifting my sprite by keyboard enter,I attempted a tutorial I discovered in rezghob weblog and nevertheless 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 , Occasion *occasion)
{

        if (keys.discover(keyCode) == keys.finish())
        {
            keys[keyCode] = std::chrono::system_clock::now();
        }

        CCLOG ("Variety of Keys: " , keys.measurement() );
}

void Level1::onKeyReleased(EventKeyboard::KeyCode keyCode, Occasion* occasion)
{
    if (keys.discover(keyCode) != keys.finish())
    {
        std::chrono::period<double> elapsed_seconds = std::chrono::system_clock::now() - keys[keyCode];
        CCLOG("Key code %d   was down for %f s", int(keyCode), elapsed_seconds.rely() );
    }
    keys.erase(keyCode);

    CCLOG("Variety of Keys:%f " , keys.measurement() );
}

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 Launched:

Use please

eventListener->onKeyReleased = …

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments