How can I make a character controller that changes positions on one click.

Hi everyone, How can I make a character controller that when a player clicks on the screen the character will move to a given position on the X Axis and when the player clicks the screen again the character will move back to its original position on the X Axis and that will just repeat when the player clicks continuously.

To make it clear there is only 2 specified position for the character for example:

The original position of the character on the X Axis is 1.65 when the player clicks the character will move to -1.65 and when the player clicks again it will move back to 1.65 and when clicks again will move again to -1.65. That’s what i’m trying to do. Im using Input.GetMouseButtonDown(0).

First, you’ll need to store the character original position, and the targeted position.

Then, you dynamically change the direction the character is moving to.

For example:

Vector2 GetCharPos()
{
	return transform.position;
}

void Start()
{
	cam = Camera.main;
	oriPos = (0, 0);
	newPos = (0, 0);
	mousePos = Input.mousePosition;
	targetPoint = (0, 0);
	speed = 10.0f;
}

void Update()
{
	if Input.GetMouseButtonDown(0)
	{
		if oriPos != (0, 0)
		{
			oriPos = GetCharPos();
			targetPoint = oriPos;
		}
		newPos = cam.ScreenToWorldPoint(mousePos.x, mousePos.y);
		targetPoint = newPos;
	}
	transform.position = Vector2.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
}