Character direction can't be changed before the character reaches a screen limit in some cases

Hello everyone!

So I have this player that goes from left to right when I hit the “right” button, and it goes from right to left when I hit the “left” button. When I hit the “left” button, I can press the “right” one right away and the player will change directions on the spot. On the other hand, if I press the “right” button, I can’t change the player’s direction before the player gets to the right limit.

Here is an image showing the situation:

Here is my script which is attached to the player:

private bool leftbutton;
private bool rightbutton;

private float x;
public float speed;
public float y;

private Vector3 vectorDir;

//function when "left" button is clicked
public void Left()
{
    if (transform.position.x > -2.0f)
    {
        leftbutton = true;
    }
}

//function when "right" button is clicked
public void Right()
{
    if (transform.position.x < 2.0f)
    {
        rightbutton = true;
    }
}

void Update()
{

    vectorDir = new Vector3(x, y);
    transform.Translate(vectorDir * speed * Time.deltaTime);

    if (leftbutton == true)
    {
        x = -1.0f;
        if (transform.position.x <= -2.0f || rightbutton == true)
        {
            leftbutton = false;
        }
    }

    if (rightbutton == true)
    {
        x = 1.0f;
        if (transform.position.x >= 2.0f || leftbutton == true)
        {
            rightbutton = false;
        }
    }

    if (rightbutton == false && leftbutton == false)
    {
        x = 0.0f;
    }

}

Any help is greatly appreciated!

this part:

 if (leftbutton == true)
 {
     x = -1.0f;
     if (transform.position.x <= -2.0f || rightbutton == true)
     {
         leftbutton = false;
     }
 }

if rightbutton is true, leftbutton will immediately set to false in update :stuck_out_tongue: maybe you can take an other construct, for example you can take an int with value 0 = stop, 1 = left, 2 = right, and set the int when you hit a button.