0
\$\begingroup\$

I'm relatively new to programming velocity and such as I used to use Unity so it was already implemented. Right now, I'm using MonoGame and have an issue with my velocity code. Whenever I decelerate, my "velocity.X" never becomes 0 it just keeps going down to numbers like "-8.775121E-10". I tried to check if it's less than or equal to 0.05 but that just causes issues.

Movement Code:

currentState = Keyboard.GetState();

        deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

        bounds.X = (int)position.X;
        bounds.Y = (int)position.Y;

        position.X += velocity.X;
        position.Y += velocity.Y;

        if (velocity.X >= MAX_ACCELERATION)
            velocity.X = MAX_ACCELERATION;
        if (velocity.X <= -MAX_ACCELERATION)
            velocity.X = -MAX_ACCELERATION;

        if (currentState.IsKeyDown(Keys.A))
        {
            if (velocity.X > -MAX_ACCELERATION)
                velocity.X -= acceleration * deltaTime;
        }
        else if (currentState.IsKeyDown(Keys.D))
        {
            if (velocity.X < MAX_ACCELERATION)
                velocity.X += acceleration * deltaTime;
        }

        Console.WriteLine("Velocity: " + velocity);
        Console.WriteLine("Current KeyState: " + currentState.IsKeyUp(Keys.A));

        prevState = currentState;

        Console.WriteLine("Prev KeyState: " + prevState.IsKeyDown(Keys.A));

        SlowDown();

SlowDown Method:

            /*if (!prevState.IsKeyUp(Keys.A) && currentState.IsKeyUp(Keys.A))
        {
            if (velocity.X >= -0.5f)
                velocity.X = 0;
        }*/

        velocity.X *= FRICTION;
\$\endgroup\$
0
\$\begingroup\$

Fixed it. For anyone having the same issue, I just added a bool variable called "isRight" and made it true when I am pressing the right key and false when pressing the left key. Then I check the velocity to see if it is less than or greater than (depending on the bool) 0.5 in the SlowDown method and set it to 0.

Code:

velocity.X *= FRICTION;

        if (isRight && velocity.X <= 0.5f)
        {
            velocity.X = 0;
        }

        if (!isRight && velocity.X >= -0.5f)
        {
            velocity.X = 0;
        }
\$\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.