Using MoveTowards to move to a players position that it gets when the object is spawned.

Hi i’m currently trying to make an object move towards the position of the player when it spawns, however i want to player to be able to move out of the way and the object to keep moving towards the players initial position when the object was spawned. However it keeps updating the players position in the Vector3.MoveTowards code.

To sum up what i want to achieve is:

  • Spawn enemy
  • Get players position on enemy spawn
  • Move towards the position of what the players position was when the enemy spawned

Here is what i’m using

public class WhiteBloodCellAI : MonoBehaviour {
	private GameObject mytarget;
	private Transform targetPos;
	public float mySpeed;
	private GameObject deathBarrior;
	// Use this for initialization
	void Start () {
		mytarget = GameObject.FindGameObjectWithTag("Player");
		deathBarrior = GameObject.FindGameObjectWithTag("DeathBarrier");
		targetPos = mytarget.transform;
	void Update () {
			transform.position = Vector3.MoveTowards(transform.position, targetPos.position, mySpeed*Time.deltaTime);
			transform.position = Vector3.MoveTowards(transform.position, deathBarrior.transform.position, mySpeed*Time.deltaTime); 	

Thanks for the help!

Make targetPos a Vector3 instead of a Transform. Initialize it in start:

targetPos = mytarget.transform.position;

And then you will use targetPos instead of ‘targetPos.position’ in line 20.

Note a Vector3 is a structure, and you get copies of structures when you do assignments. Transforms are classes and you get references to classes when you do assignments. So by using Vector3, you get a copy of the position that does not get updated as the target changes position.