- Home /
 
Move a object and then return , like loop
Hi Guys, I was wondering how can i move an enemy to the left and to the right in a short space, like an infinite loop.
I'm trying to think in a good method, but all that i've got until now is this
 void Move()
     {
         time= Time.deltaTime;
         if (time<= timePosition) 
         {
             transform.Translate(-speed*Time.deltaTime,0,0);
         }
         if (time > timePosition) 
         {
             transform.Translate(speed*Time.deltaTime,0,0);
         }
         
     }
 
               basically it's a repeated movement applied in the update.
Answer by Injourn · Apr 18, 2016 at 07:49 PM
I maybe late but I would recommend using a coroutine rather than Update. Then by doing something like this....
 IEnumerator Move(){
      bool goingLeft = true;
      transform.Translate(-speed*Time.deltaTime,0,0); 
      while(true) {
           yield return new WaitforSevonds(timePosition);
           goingLeft ? transform.Translate(speed*Time.deltaTime,0,0) : transform.Translate(speed*Time.deltaTime,0,0);
           goingLeft ? false; true;
      }
 } 
 
              Thanks for the answer, I've studied my code and did it again. Now it is working like i wanted.
 public float walkSpeed = 1.0f;      // Walkspeed
     public float wallLeft = 0.0f;       // Define wallLeft
     public float wallRight = 5.0f;      // Define wallRight
     float walkingDirection = 1.0f;
     Vector2 walkAmount;
     float originalX; // Original float value
 
     private bool olhandoDireita = true;
     
     
     void Start () {
         this.originalX = this.transform.position.x;
     }
     
     // Update is called once per frame
     void Update () {
         walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;
         if (walkingDirection > 0.0f && transform.position.x >= originalX + wallRight) {
             walkingDirection = -1.0f;
             Flip();
         } else if (walkingDirection < 0.0f && transform.position.x <= originalX - wallLeft) {
             walkingDirection = 1.0f;
             Flip();
         }
         transform.Translate(walkAmount);
     }
                 Answer by tanoshimi · Apr 20, 2016 at 02:15 PM
You do this in a single line using Mathf.PingPong.
 void Update() {
     transform.position = new Vector3(Mathf.PingPong(Time.time, 3), transform.position.y, transform.position.z);
 }
 
              Your answer
 
             Follow this Question
Related Questions
Move object to several locations 2 Answers
Sprite moving too far/fast 1 Answer
Vector 3 - move on only one axis 0 Answers
How do you make an object go left and right? 1 Answer
Object not moving,Object not moving in any direction 1 Answer