Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make an object move endlessly?

I want to move an object from position A to position B on X axis endlessly. But it does move and comeback only once. How to make it continuosly? I’ve tried Vector3.Lerp or just creating new Vector3 but it only teleports.

`

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovingTarget : MonoBehaviour
{
    [SerializeField] private Vector3 firstPosition = new Vector3(-14f, 2.5f, 17f);
    [SerializeField] private Vector3 secondPosition = new Vector3(14f, 2.5f, 17f);
    
   
    public float speed = 10f;
  

    void Start()
    {
       transform.position = firstPosition;
    }
    
    void Update()
    {

      

      
            transform.position = Vector3.MoveTowards(transform.position, secondPosition, Time.deltaTime * speed);
       
        if(transform.position == secondPosition)
        {
            secondPosition = firstPosition;
        }

       



    }
}

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I don’t use Unity, but since nobody else answered….

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovingTarget : MonoBehaviour
{
    [SerializeField] private Vector3 firstPosition = new Vector3(-14f, 2.5f, 17f);
    [SerializeField] private Vector3 secondPosition = new Vector3(14f, 2.5f, 17f);
    private Vector3 target;

    public float speed = 10f;

    void Start()
    {
       transform.position = firstPosition;
       target = secondPosition;
    }
    
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
       
        if (transform.position == firstPosition)
        {
            target = secondPosition;
        }
        else if (transform.position == secondPosition)
        {
            target = firstPosition;
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading