- Home /
Vector3.lerp and then wait
I'm trying to make the character go to tree, wit a few seconds, go to the camp and then back to the tree ect. but its not working my code is:
using UnityEngine; using System.Collections;
 
               public class ForagerAi : MonoBehaviour {
  public int Health = 6;
 public Transform Tree;
 public Transform Camp;
 public int moveSpeed;
 public int myAcorns;
 private Transform myTransform;
 // Use this for initialization
 void Awake() {
     myTransform = transform;
 }
 void Start () {
     GameObject t = GameObject.FindGameObjectWithTag("ForagerTree");
     Tree = t.transform;
     GameObject c = GameObject.FindGameObjectWithTag("Camp");
     Camp = c.transform;
     myAcorns = 0;
 }
 // Update is called once per frame
 void Update () {
     if(myAcorns == 0) {
         transform.position = Vector3.Lerp(myTransform.position, Tree.position, Time.deltaTime * moveSpeed);
     }
     if(myAcorns == 5) {
         transform.position = Vector3.Lerp(myTransform.position, Camp.position, Time.deltaTime * moveSpeed);
     }
     if(Health == 0) {
         Destroy(gameObject);
     }
 }
 public void WhereAmI() {
     if(myTransform.position == Tree.position) {
         myAcorns = 5;
     }
     if(myTransform.position == Camp.position) {
         myAcorns = 0;
     }
 }
 } 
How do I make the character wait? Thanks in advance.
               Comment
              
 
               
              Answer by Berenger · May 03, 2012 at 05:32 AM
WhereAmI doesn't seem to be called. Anyway, the position wouldn't be equal and the character would end up buzzing around a point. Take a look a that code and the comments :
 public float speed, arrivalDistance, wait;
 public Transform tree, camp;
 
 private IEnumerator Start()
 {
     while( Application.IsPlaying )
     {
         // Wait until the character has reached the tree
         yield return StartCoroutine( GoTo(tree.position) );
 
         // Wait "wait" seconds
         yield return new WaitForSeconds( wait );
 
         // Wait until the character has reached the camp
         yield return StartCoroutine( GoTo(camp.position) );
 
         // Wait "wait" seconds
         yield return new WaitForSeconds( wait ); 
     }
 }
 
 // Reach a destination
 private IEnumerator GoTo( Vector dest )
 {
     // Check the sqMag to spare a Sqrt
     while( (dest - transform.position).sqrMagnitude > arrivalDistance )
     {
         transform.position = Vector3.Lerp(transform.position, dest, Time.deltaTime * speed);
         yield return null;
     }
 }
Your answer
 
 
             Follow this Question
Related Questions
Using Lerp in a Constant Moving Object 1 Answer
Not Sure How to Get Around this Problem 1 Answer
Vector3.Lerp making my object invisible. 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                