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!