Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# MonoGame – backwards player movement

I’m working on a school project, in which I’m making an astroids clone.
I’ve been working on player movement and have implemented the code below.

I’m getting some weird behavior when trying to move the player sprite backward and I’m having a hard time understanding the math behind it.

I’ve commented below where the problem is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

position = velocity + position;

        if (Keyboard.GetState().IsKeyDown(Keys.Left)) rotation -= 0.1f;
        if (Keyboard.GetState().IsKeyDown(Keys.Right)) rotation += 0.1f;

        if (Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            velocity.X = (float)Math.Cos(rotation) * tangentialVelocity;
            velocity.Y = (float)Math.Sin(rotation) * tangentialVelocity;

        }

        //this is where I need help

        if (Keyboard.GetState().IsKeyDown(Keys.Down))
        {
            velocity.X = (float)Math.Cos(rotation) - tangentialVelocity;
            velocity.Y = (float)Math.Sin(rotation) - tangentialVelocity;

        }
        else if (velocity != Vector2.Zero)
        {
            float i = velocity.X;
            float j = velocity.Y;

            velocity.X = i -= friction * i;
            velocity.Y = j -= friction * j;

        }

>Solution :

It seems to me like the logic for forwards/backwards thrust should be as follows:

Given some variable like int thrustPower = 1.0f;

if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
    velocity.X += (float)Math.Cos(rotation) * thrustPower;
    velocity.Y += (float)Math.Sin(rotation) * thrustPower;
}

if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
    velocity.X -= (float)Math.Cos(rotation) * thrustPower;
    velocity.Y -= (float)Math.Sin(rotation) * thrustPower;
}

So that if either Keys.Up or Keys.Down is pressed, the velocity on each axis will scale by the normal amount of ThrustPower projected onto that axis.

This also gets around the problem of having to deal with what you call tangentialVelocity, but I assume should actually be radialVelocity or just speed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading