0
\$\begingroup\$

I've implemented a basic Keyboard Input manager:

#include "UserIO.h"


UserIO::UserIO(GameManager* game, Physics* physics)
{
    this->game = game;
    this->physics = physics;
}

UserIO::~UserIO()
{
}

void UserIO::checkInput()
{
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    {
        physics->moveLeft();
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    {
        physics->moveRight();

    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    {
        physics->moveUp();
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    {
        physics->moveDown();
    }

}

The physics manager increments the player's velocity as follows:

void Physics::moveRight()
{
    //ball->setVelX(ball->getVelx()+0.005f);
    ball->setX(ball->getVelx() + 0.001);

}

void Physics::moveUp()
{
    ball->setVelY(ball->getVely() + 0.001f);
}

void Physics::moveLeft()
{
    ball->setVelX(ball->getVelx() - 0.001f);
}

void Physics::moveDown()
{
    ball->setVelY(ball->getVely() - 0.001f);
}

void Physics::updatePlayerPos()
{
    //dampen velocity
    ball->setVelX(ball->getVelx() * dampen);
    ball->setVelY(ball->getVely() * dampen);

    ball->setX(ball->getX() + ball->getVelx());
    ball->setY(ball->getY() + ball->getVely());
}

And my main loop:

while (window->isOpen())
    {


        window->clear();
        user->checkInput();
        physics->tick();
        render->draw();

    }

The idea is for the player object (circle) to accelerate as one of the keys is pressed. The "tick" method calls "updatePlayerPos" to calculate displacement.

A "dampen" variable ensures the ball decelerates while no keys are pressed.

When running the program, SFML seems somewhat receptive to keyboard strokes, however the motion of the ball is completely erratic: while a key is pressed, the ball will remain stationary for a while, and then zoom off. I've tried a different combination of velocity values and nothing improves. I also tried removing the acceleration aspect altogether, and having the ball's displacement proportional to the length of time the key is pressed (e.g. if "right key" is pressed, add 0.1 to x). Sadly no change.

I'm now starting to think the issue lies with the game loop and/or SFML, as opposed to the physics. Is it possible that keystrokes are being missed? Would a fixed timestep help the situation?

\$\endgroup\$
-2
\$\begingroup\$

What exactly do you mean by "zoom off"?
If you mean disappear then either way I suggest trying to log those values (printf / cout >>) to a console so you can see whether its the speed or the position.
Basically if the math is correct. You might also want to see what happens if you set the acceleration to 0 or read out when a button press occurs

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.