[SOLVED] How to make Keyboard button to continuously call callback function when hold-pressed Cocos2d-x

I would like to ask how to make a particular sprite to move when the keyboard button is pressed?

I have this following code:

void MainGameScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event * event)
    {
    	if (keyCode == EventKeyboard::KeyCode::KEY_LEFT_ARROW)
    	{
    		cocos2d::Vec2 newPos = cocos2d::Vec2(mElapsedTime * -mBlockVelocity, 0);
    		mSprite->setPosition(mSprite->getPosition() + newPos);
    	}
    	else if (keyCode == EventKeyboard::KeyCode::KEY_RIGHT_ARROW) 
    	{
    		cocos2d::Vec2 newPos = cocos2d::Vec2(mElapsedTime * mBlockVelocity, 0);
    		mSprite->setPosition(mSprite->getPosition() + newPos);
    	}
    	else if (keyCode == EventKeyboard::KeyCode::KEY_UP_ARROW) 
    	{
    		cocos2d::Vec2 newPos = cocos2d::Vec2(0 , mElapsedTime * mBlockVelocity);
    		mSprite->setPosition(mSprite->getPosition() + newPos);
    	}
    	else if (keyCode == EventKeyboard::KeyCode::KEY_DOWN_ARROW) 
    	{
    		cocos2d::Vec2 newPos = cocos2d::Vec2(0, mElapsedTime * -mBlockVelocity);
    		mSprite->setPosition(mSprite->getPosition() + newPos);
    	}
    }

The problem with this is that every time I pressed a button, it doesn’t perform this function again even though I hold-press a button.

How can I continuously call a callback function so I could update the speed and position of the sprite based on elapsed time since last frame update?

Thank you and have a great day!

1 Like

This is brilliant. I found a tutorial here from GamesFromScratch:

http://www.gamefromscratch.com/post/2014/10/07/Cocos2d-x-Tutorial-Series-Handling-the-Keyboard.aspx

This definitely what I was looking for! I hope this will help someone in the future.

1 Like