Vector3.MoveTowards issues

Hi there. I’m having some problems with Vector3.MoveTowards. I’m trying to get the object to move to a location then return to the start location once it has reached that position. Here’s my code:

void movePlayer (){
				Vector3 targetPos = new Vector3 (0, 0.75f, 0);
				Vector3 start = new Vector3 (4.5f, 0.75f, 0.05f);
				transform.position = Vector3.MoveTowards (transform.position, targetPos, speed * Time.deltaTime);
				if (transform.position == targetPos) {
						transform.position = Vector3.MoveTowards (transform.position, start, speed * Time.deltaTime);
				
				}


	}

All the code is currently doing is moving the object to the location and not moving back. All help appreciated.

That is because your steps towards the start only occur if the object is at its target. As soon as your object takes its first step away from the target, that condition is no longer true, so the next frame it will move towards the target again.

You might be able to see this tiny back and forth motion occurring every frame.

To fix this, you could use a variable to act as a “flag” which stores whether the object should be travelling towards the target or towards the start.

bool reachedTarget = false;

void movePlayer (){
	 Vector3 targetPos = new Vector3 (0, 0.75f, 0);
	 Vector3 start = new Vector3 (4.5f, 0.75f, 0.05f);
	 if (!reachedTarget)
	 {
		transform.position = Vector3.MoveTowards (transform.position, targetPos, speed * Time.deltaTime);
		if (transform.position == targetPos) reachedTarget = true;
	} else {
		transform.position = Vector3.MoveTowards (transform.position, start, speed * Time.deltaTime);		
	}
}

Note the variable “reachedTarget” is outside the function, because its state has to persist from one frame to the next.