Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Keyboard problem  (Read 1553 times)

0 Members and 1 Guest are viewing this topic.

jagslash

  • Newbie
  • *
  • Posts: 3
    • View Profile
Keyboard problem
« on: October 10, 2013, 05:31:08 pm »
I recently bought the SFML game development book and I ran into a bit of a problem. When I try to move the ship the first key press I do will move in the opposite direction than it should, but after that it works perfectly. I'm not sure what would be causing this and I checked my code many times.

Thanks for the help!

Clockwork

  • Newbie
  • *
  • Posts: 47
    • View Profile
Re: Keyboard problem
« Reply #1 on: October 10, 2013, 05:58:09 pm »
If you could post the relevant code, than we may be able to help you.  But I can't do much for you if I can't see the code.

Thanks.

jagslash

  • Newbie
  • *
  • Posts: 3
    • View Profile
Re: Keyboard problem
« Reply #2 on: October 10, 2013, 06:27:37 pm »
Code: [Select]
void Game::run(){
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (mWindow.isOpen()){
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TimePerFrame){
timeSinceLastUpdate -= TimePerFrame;
processEvents();
update(TimePerFrame);
}

render();
}
}
void Game::processEvents(){
sf::Event event;
while (mWindow.pollEvent(event)){
switch (event.type){
case sf::Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
case sf::Event::Closed:
mWindow.close();
break;

}
}
}
void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed){
if (key == sf::Keyboard::W)
mIsMovingUp = isPressed;
else if (key == sf::Keyboard::S)
mIsMovingDown = isPressed;
else if (key == sf::Keyboard::A)
mIsMovingLeft = isPressed;
else if (key == sf::Keyboard::D)
mIsMovingRight = isPressed;
}

void Game::update(sf::Time deltaTime){
sf::Vector2f movement(0.f, 0.f);
if (mIsMovingUp)
movement.y -= PlayerSpeed;
if (mIsMovingDown)
movement.y += PlayerSpeed;
if (mIsMovingLeft)
movement.x -= PlayerSpeed;
if(mIsMovingRight)
movement.x += PlayerSpeed;

mPlayer.move(movement * deltaTime.asSeconds());
}


As I said before it will work, but it won't work the first time. For example I can press A and it will go right, but after pressing it again it will go left as it should.

jagslash

  • Newbie
  • *
  • Posts: 3
    • View Profile
Re: Keyboard problem
« Reply #3 on: October 10, 2013, 06:46:05 pm »
I found the fix! Sorry if I wasted anyone's time. I forgot to set the mIsMovingUp, etc. to false.

 

anything