0
\$\begingroup\$

I'm trying to make a nice controls for my game, but I can't achieve enough SMOOTHNESS.

if (kbState.GetPressedKeys().Length != 0 && _direction != Vector2.Zero)
    {
        _direction.Normalize();
        _position += _direction * (_speed * (float)gameTime.ElapsedGameTime.TotalSeconds);
    }
    else
        _direction = Vector2.Zero;

    if (kbState.IsKeyDown(Keys.W))
    {
        _direction += new Vector2(0, -1f);
    }
    if (kbState.IsKeyDown(Keys.S))
    {
        _direction += new Vector2(0, 1);
    }

    if (kbState.IsKeyDown(Keys.D))
    {
        _direction += new Vector2(1, 0);
    }

    if (kbState.IsKeyDown(Keys.A))
    {
        _direction += new Vector2(-1, 0);
    }

There is the code. Could you help me a little and give an advice how to make character stop smoothly. I tried many options, but could'nt find any that fit. help this guy

\$\endgroup\$
  • \$\begingroup\$ Move less each frame? \$\endgroup\$ – Doorknob Jan 21 '13 at 0:03
  • \$\begingroup\$ Does this help? stackoverflow.com/questions/6841575/… \$\endgroup\$ – user24821 Jan 21 '13 at 0:32
  • 1
    \$\begingroup\$ You want it to stop smoothly? like some sort of pseudo-friction? \$\endgroup\$ – Luis Estrada Jan 21 '13 at 1:39
  • 1
    \$\begingroup\$ Luis, exactly, pseudo-friction! \$\endgroup\$ – edwing Jan 21 '13 at 12:12
1
\$\begingroup\$

Here is how I usually simulate friction:

    Vector2 Velocity;
    float Friction; // In pixels / second^2

    void ApplyFriction() {
        if (Velocity.X > 0) Velocity.X -= Friction;
        if (Velocity.X < 0) Velocity.X = 0;
    }

You then put the function at the end of your character's presumed Update() method.

If you want constant movement, you can set Friction to 0 until you want it enabled again (as in, when you want your character to stop). (y)

PROTIP: You can transform this in a Gravity function by turning the code into Velocity.Y += GravitySpeed; if (Velocity.Y > TerminalVelocity) Velocity.Y = TerminalVelocity!

\$\endgroup\$
1
\$\begingroup\$

You need velocity Assuming fixed time step:

if(noKeysPressed)
{
    _velocity =* 0.5f; //adjust ratio to your needs
}
else
{
    //change velocity how you want
}

_position += velocity; //modify position even if no key is pressed
\$\endgroup\$
  • \$\begingroup\$ Hm, looks like what i need, gonna try this \$\endgroup\$ – edwing Jan 21 '13 at 12:13

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.