How to make object go from A to B and from B to A with same key

Hello! Im trying to make my first game, and i need some help on how to make my object move from A to B when i press “a”, and from B to A when i press “a” again. I have found a script that moves my object from A to B, but i can’t figure out how to make it go from B to A when i press “a” again.
120589-help.png

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class lerp : MonoBehaviour { 

    public GameObject player;

    private Vector3 pos1;
    private Vector2 pos2;

    private float distance = 4.7f;

    private float time = 0.05f;

    private float currentTime = 0;

    private bool keyHit = false;


	// Use this for initialization
	void Start () {
        pos1 = player.transform.position;
        pos2 = player.transform.position + Vector3.right*distance;
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKeyDown ("a")) { keyHit = true; }
        if (keyHit == true)
        {
            currentTime += Time.deltaTime;
            if (currentTime >= time) { currentTime = time;
            }
            float Perc = currentTime / time;
            player.transform.position = Vector3.Lerp(pos1, pos2, Perc);
            }
	}
}

Hi, you could add a variable to know in which position you are for example:

int currentPos
if (player.transform.position == pos1)
{
currentPos = 1;
}
else if (player.transform.position == pos2)
{
currentPos = 2;
}
else
{
currentPos = 0;
}

if (Input.GetKeyDown ("a")) {
keyHit = true;
}
         if (keyHit == true)
         {
             currentTime += Time.deltaTime;
             if (currentTime >= time)
             {
             currentTime = time;
             }
             float Perc = currentTime / time;

             if (currentPos == 1)
             {
             player.transform.position = Vector3.Lerp(pos1, pos2, Perc);
             }
             else if (currentPos == 2)
             {
             player.transform.position = Vector3.Lerp(pos2, pos1, Perc);
             }
             }
     }

Then you must probably set keyHit to false again when the player reached the Pos. Ask if you need more.

Hey @MT369MT! Thanks for the tips. How do i make the var know if the object is in pos1 or pos2? I’m very new at coding, just started a couple days ago :confused: