(SOLVED)Player need to reach lanes first before can move again

i had script that make player switch between 3 lanes, left, middle, right with starting position on the middle.

player can move perfectly but it’s not what I want.

i want to make when player move for example

player position on middle and want to move to the left.
player need to reach left first before being able to move again.

and player can’t do this

player position on middle,
player move to left, and if we press right, the player can’t move into right.

I’m sorry for my English.

the code would be something like this.

private List<Vector2> lanePosisition = new List<Vector2>()
    {
        new Vector2(-4.3f,-2.7f),
        new Vector2(0.5f, -2.7f),
        new Vector2(4.3f,-2.7f)
    };
    public int currentLane = 1;
    public float maxSpeed = 1;

void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            currentLane--;
            if (currentLane < 0)
            {
                currentLane = 0;
            }
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            currentLane++;
            if (currentLane > 2)
            {
                currentLane = 2;
            }
        }
        var maxDistance = maxSpeed * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, lanePosisition[currentLane], maxDistance);

    }

This is my current code, I’ve also tried several ide like making bool function or use Couruntine wairForSecond but it didn’t works.

Something like this maybe? The idea being that you move the player each frame at the start of the method, and then check how close the player is to the target position. If they’re not close enough, you return before checking for the next input. You only really need to check the absolute x val, but I used .Distance to keep things nice and simple.

void Update()
    {
      var maxDistance = maxSpeed * Time.deltaTime;
      transform.position = Vector2.MoveTowards(transform.position, lanePosisition[currentLane], maxDistance);
     
      float minDistanceBeforeNextMove = 0.1f;
      if (Vector2.Distance(transform.position,lanePosisition[currentLane]) > minDistanceBeforeNextMove) return;

        if (Input.GetKeyDown(KeyCode.A))
        {
            currentLane--;
            if (currentLane < 0)
            {
                currentLane = 0;
            }
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            currentLane++;
            if (currentLane > 2)
            {
                currentLane = 2;
            }
        }
    }
1 Like

uwooh Thank you so much. it works!

1 Like