- Home /
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 () {
if(mytarget){
transform.position = Vector3.MoveTowards(transform.position, targetPos.position, mySpeed*Time.deltaTime);
}
else{
transform.position = Vector3.MoveTowards(transform.position, deathBarrior.transform.position, mySpeed*Time.deltaTime);
}
}
}
Thanks for the help!
Answer by robertbu · Apr 12, 2013 at 08:49 PM
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.
Your answer
Follow this Question
Related Questions
Create a straight gradient equation with a grid of 3d objects 1 Answer
Following another object's position/rotation like parent/child relationship? 4 Answers
How do you set the initial value of a variable to an objects current position in unity? 1 Answer
Create an animation with variables? 1 Answer
C# move y position of object not working 2 Answers