- Home /
 
move gameobject into a random position and the spawn an enemy
hello, this is the script that I did.
 void Start () 
 {
     posFinale = new Vector3(Random.Range (-17.0f,18.0f),Random.Range (-10.0f,11.0f),0);
 }
 
 void Update () 
 {
     transform.Translate ((posFinale - transform.position)* speed * Time.deltaTime);
     if ((transform.position == posFinale) && !(fatto))
     {
         fatto = true;
         Instantiate(add,transform.position, Quaternion.identity);
         Destroy (gameObject);
     }
     Debug.Log (posFinale);
 }
 
               But I have a problem, when it comes to the location is not that precise so do not spawn the enemy.
I also tried with vector3.lerp but does the exact same thing
Is there another way to do this?
Answer by robertbu · Jul 16, 2014 at 05:42 PM
As @iwaldrop suggests, Vector3.MoveTowards() will work. Lerp() will work if you in a linear fashion (i.e. the final parameter be an increasing fraction between 0 and 1. You can also make your existing code work. The problem is this check:
  if ((transform.position == posFinale) && !(fatto))
 
               The chance of transform.position being exactly equal to posFinal is small. So you can instead do the check this way:
 if (Vector3.Distance(transform.position, posFinale) < threshold && !(fatto))
 
               'threshold' is either a variable you define or some constant. It is a small value that defines close enough.
I thought I had a similar method but did not know how to do it, thanks a lot!
Your answer