moving left and right

hello i want a script to move my object right for some distance and then return to the first position automaticaly
but smooth movement.!

public float distance;
public float obstaspeed;

void Start () {
}
void FixedUpdate () {
StartCoroutine(MyCoroutine());;
}

IEnumerator MyCoroutine() {

transform.position += new Vector3 (distance * Time.deltaTime/5 * obstaspeed , 0.0f , 0.0f);

yield return new WaitForSeconds(2);

transform.position += new Vector3 (-distance * 2 * Time.deltaTime/5 * obstaspeed , 0.0f , 0.0f);

yield return new WaitForSeconds(2);

transform.position += new Vector3 (distance * 2 * Time.deltaTime/5 * obstaspeed , 0.0f , 0.0f);

I made this script but the movement after a while is not smooth
PLEASE HELP I KNOW THIS IS AN EASY SCRIPT BUT MY MIND IS REALLY TIRED RIGHT NOW I
CANT FIND A SOLUTION

thanks in advance

Eh, FixedUpdate runs every frame. So about 100 times a second you’re starting a new coroutine to make the object move multiple times.

What you want to do is put the StartCoroutine in the Start function.

Then in the Coroutine make it look like this:

IEnumerator MyCoroutine() {

while(Time.timeSinceLevelLoad < 2){
transform.position += new Vector3 (distance * Time.deltaTime/5 * obstaspeed , 0.0f , 0.0f);
yield return null;
}

while(Time.timeSinceLevelLoad < 4){
transform.position += new Vector3 (distance * Time.deltaTime/5 * obstaspeed , 0.0f , 0.0f);
yield return null;
}

while(Time.timeSinceLevelLoad < 6){
transform.position += new Vector3 (distance * Time.deltaTime/5 * obstaspeed , 0.0f , 0.0f);
yield return null;
}

}

yield return null allows it to run 1 frame before continuing. The while loop will keep running that code until 2 seconds have passed, then the next one at 4 seconds, etc.

1 Like

awesome thanks mate

but how can i make this go on forever? i mean repeat this left and right movement??

Wrap in all in a while(true){yield return null;} loop

I would seriously suggest using LeanTween for this type of work - it greatly simplifies the task, and creates significantly more readable and maintainable code. Oh and its performance is great!

LeanTween is available for free in the asset store: LeanTween - A tweening engine that is up to 5x faster than competing engines! - Community Showcases - Unity Discussions

I have no association with LeanTween, I just really like the product.

1 Like

its ok i found a nice solution!! thanks mate!!

1 Like