Since the solution was given in a comment but not implemented in the answer, here is some kind of "code review"
Key binding
This code actually uses sf::Keyboard::isKeyPressed and sf::Keyboard::isKeyReleased , which need to be called every cycle, while a simple logical switch when the key is pressed / released can work using events.
while (renderWindow.pollEvent(event)) { if (event.type == sf::Event::EventType::Closed) renderWindow.close(); }
The event used in the main loop also contains information about KeyEvents, but is not used in this way. I suggest sending evet while playing eac when an event occurs:
while (renderWindow.pollEvent(event)) { switch(event.type){ case sf::Event::EventType::Closed: renderWindow.close(); break; case sf::Event::KeyPressed: case sf::Event::KeyReleased: myPlayer.keyEvent(event); break; } }
The keyEvent function in the player should look like this:
void player::keyEvent(sf::Event event){ //Keycode of your keyboard arrows goes from 71 to 74 if (event.key.code >= 71 && event.key.code <= 74){ //Gets the array ID from the enumeration value int ID = event.key.code - 71; //Stores false if the key is release, and true if it pressed keys[ID] = (event.type == sf::Event::KeyPressed); } }
Depends on each array value in Player.h:
private: bool keys[4];
Motion
Now all you have to do is call the player's update () function in the game loop every second:
if (clock.getElapsedTime().asSeconds() > 1.0f) { if (rectSourceSprite.left == 96) rectSourceSprite.left = 0; else rectSourceSprite.left += 32; sprite.setTextureRect(rectSourceSprite); myPlayer.update(); clock.restart(); }
In the update() function, then you will create a motion vector based on the keystroke:
void player::update() { sf::Vector2f movementVector(0,0); //Left if (keys[0]){ movementVector.x -= movementSpeed; //Sends the sprite Rectangle position based on the movement type move(32); } //Right if (keys[1]){ movementVector.x += movementSpeed; move(64); } //Up if (keys[2]){ movementVector.y -= movementSpeed; move(96); } //Down if (keys[3]){ movementVector.y += movementSpeed; move(0); } }
The move function then moves your sprite position depending on the motion vector and counter, then the sprite will be set.
The movement counter will be increased to 30, and your player can only move when this counter is 0, 10 or 20:
void move(int spritePos){
There are several ways to do this, just the way I did it