key code movement. Stuck on if statements.

Every time a key comes up i reduce speed to 0.
How to to make so that if the A KEY is down, and D KEY comes up it won’t set the speed to 0.
I’ve tried everything I could google. I think I need help from someone that knows enough.
Any help would be greatly appreciated.

 if (Input.GetKeyDown(KeyCode.A))
        {
            speed = -speedX;
        }
        if (Input.GetKeyUp(KeyCode.A) && Input.GetKeyDown(KeyCode.D))
        {

            speed = speedX;
 }
        
else if (Input.GetKeyUp(KeyCode.A)) 
{
            speed = 0;
           
        }
     
       
       
        if (Input.GetKeyDown(KeyCode.D))
        {
            speed = speedX;
        }
        if (Input.GetKeyUp(KeyCode.D))
        {
           
                speed = 0;
           
        }

Use the InputManager, put it in a vector and apply that to the transform.

Vector3 input = Input.GetAxis("Horizontal");
player.transform.position += input * Time.deltaTime;

It’s 2d game and I don’t think that will work with the rest of my player manager script. I’ll definitely give it a shot though. Thank you for such a quick reply.

Didn’t work. It won’t allow the vector 3 statement.

I think this is what you’re after

if (Input.GetKeyDown(KeyCode.A))
{
    speed = -speedX;
}
if (Input.GetKeyDown(KeyCode.D))
{
    speed = speedX;
}


if (Input.GetKeyUp(KeyCode.A) && !Input.GetKey(KeyCode.D))
{
    speed = 0;
}
if (Input.GetKeyUp(KeyCode.D) && !Input.GetKey(KeyCode.A))
{
    speed = 0;
}
1 Like

Alternative approach:

int speed = 0; 
if (Input.GetKey(KeyCode.A))
  speed -= speedX; 
if (Input.GetKey(KeyCode.D))
  speed += speedX;

If both A and D are held down, they cancel each other out, and speed is back to 0. This is actually the logic behind Input.GetAxis, so you may as well use that instead.

Note: It returns a float. You can cast it to int if needed.

1 Like

Bro, you’re my f####### hero!

Wow, that’s nice to hear! thanks.

1 Like

I’m so serious. Thank you so very much. I’ve been struggling for a week and it was that simple. You did a good thing, and I GREATLY appreciate you taking your time to help me.