- Home /
How do I loop an object from A to B and start again at A
Hi guys, this is my 1st post here and I'm wondering how to make an object (a day & night sky) loop as it goes from A to B and start again at A. It's a sky image that will loop over and over to simulate the day and night cycle.
When I run the code, the sky just keeps on moving in the y axis. Any suggestions is appreciated :)
// erge
using UnityEngine;
using System.Collections;
public class dayNightCycle : MonoBehaviour {
public float speed = -1f;
private float startPos = -7.1f;
private float endPos = 170f;
private float currentPos;
void Update () {
currentPos = transform.position.y;
transform.Translate(0, 0, speed * Time.deltaTime);
if(currentPos == endPos){
SetTransformY(startPos);
}
}
void SetTransformY(float n){
transform.position = new Vector3(transform.position.x, n, transform.position.z);
}
}
Answer by robertbu · Jun 05, 2013 at 09:37 PM
You have one problems and one potential problem here. The first is that you are doing this comparison:
if(currentPos == endPos){
Seldom will currentPos land exactly on 'endPos.' Usually it will skip over the value, being less than endPos one frame, and more than endPos the next frame. Change the check to:
if(currentPos >= endPos){
The second potential problem is that you are checking the the 'Y' position, but your Translate() code moves your object in the local 'Z' direction. So your forward of your object needs to be at least partly facing in the up direction.
Thanks, it worked! What a miss from my side haha ;) I need to sleep now... Thanks again!
Your answer
Follow this Question
Related Questions
Complex object scaling 0 Answers
Multiple Cars not working 1 Answer
making an object move to a certain point 3 Answers
Distribute terrain in zones 3 Answers
Objects seemingly not being instantiated after touch. 1 Answer