Advertisement

What's the issue with my movement code?

Started by April 25, 2021 12:09 AM
1 comment, last by JoeJ 3 years, 7 months ago
 if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))  
{
 if (velocity.y > -_maxVelocity)
  velocity.y -= _accel;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) // when going from W to S there is a noticeable friction delay before moving // we should check this eventually
{
 if (velocity.y < _maxVelocity)
  velocity.y += _accel;
}
else
{
 Clamp(velocity.y, 0.f, 5.f);
 Clamp(velocity.x, -5.f, 0.f);

 if (velocity.y > 0.f)
 {
  velocity.y -= _deccel;
 }
 else if (velocity.y < 0.f)
 {
  velocity.y += _deccel;
 }
}
// X Movement
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
 if (velocity.x > -_maxVelocity)
  velocity.x -= _accel;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
 if (velocity.x < _maxVelocity)
  velocity.x += _accel;
}
else
{
 Clamp(velocity.x, 0.f, 5.f);
 Clamp(velocity.x, -5.f, 0.f);

 if (velocity.x > 0.f)
 {
  velocity.x -= _deccel;
 }
 else if (velocity.x < 0.f)
 {
  velocity.x += _deccel;
 }
}

Move(velocity * dt.asSeconds());

Elit3d said:
Clamp(velocity.y, 0.f, 5.f); Clamp(velocity.x, -5.f, 0.f);

You wrote x but meant y, i guess.

Elit3d said:
Clamp(velocity.x, 0.f, 5.f); Clamp(velocity.x, -5.f, 0.f);

like here, but his won't work as it sets to zero depending on sign.
You likely wanted vel = clamp(vel, -5, 5);

Notice those clamps never happen as long as we keep the key pressed, so likely you want to move the clamping logic outside of key press conditions.

If you want to model movement with constant acceleration as it seems, the proper way usually is:

const float dt = 0.16f;
const float K = 5; // constant acceleration
float acceleration = 0;
if (KeyDown('LEFT') acceleration = -K;
if (KeyDown('RIGHT') acceleration = K;
velocity += acceleration * dt;
position += v * dt;

Notice position is affected by squared timestep, which is missing in your code.

This topic is closed to new replies.

Advertisement