- Home /
Orbit over 1 hour with acurate timer
I'm trying to create a 2D day & night cycle with a sun orbiting a planet around the z axis taking an hour to fully rotate. I need a timer to capture the hours / days past since the game started which syncs perfectly with the current orbit of the sun.
So far I have created the rotation and it works pretty well, however my timer goes off track by the second orbit. Is there a way to sync my hour, day floats with the rotation of the sun?
Cheers
private float rotateTime = 1.0f; // 1 hour.
private float degressToRotate;
public float hours;
public float days;
void Start()
{
InvokeRepeating("AddHours", 150.0f, 150.0F);
}
void Update ()
{
degressToRotate = (360/(rotateTime*60*60)) * Time.deltaTime;
gameObject.transform.Rotate(0f, 0f, degressToRotate);
}
void AddHours()
{
if(hours >= 24f)
{
hours = 0f;
gameObject.transform.Rotate(0f, 0f, 0f);
days++;
}
else {
hours++;
}
}
Answer by Baste · Feb 17, 2015 at 08:44 AM
Rotation, hour and day are not values you should be setting separately - they'll get out of sync eventually, no matter how accurate you are with how you try to sync them.
Instead, read of Time.time, and use that to set each of the other values. This example uses a public float field that gives the length of day, and uses Gizmos to show that the correct day and hour is being set.
Note that this will have to be attached to the point of rotation, and whatever's rotating needs to be a child object of that. That's what you're already doing, but just to be safe.
public float dayLength;
float rotationSpeed;
void Start()
{
rotationSpeed = (1 / dayLength) * 360f;
}
// Update is called once per frame
void Update()
{
transform.eulerAngles = new Vector3(0, 0, Time.time * rotationSpeed);
}
private int GetHour()
{
return (int)((Time.time / (dayLength / 24)) % 24);
}
private int GetDay()
{
return (int)(Time.time / dayLength);
}
void OnDrawGizmos()
{
if (Application.isPlaying)
UnityEditor.Handles.Label(transform.position, "Day: " + GetDay() + " Hour: " + GetHour() + " Real time: " + Time.time);
}
thanks for that much appreciated, I would like to test it out but I getting the following error.
transform.rotation assign attempt for 'Sun' is not valid. Input rotation is { NaN, NaN, NaN, NaN }.
UnityEngine.Transform:set_eulerAngles(Vector3)
This solution will still get out of sync after several days. You really want a fully deter$$anonymous$$istic system, where you calculate the position/rotation of the sun each frame based on the time, rather then incremental rotation that will accumulate rounding errors.
oops yeah, thanks works perfectly now :) 88 in-game days and in perfect sync.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Making a Timer Out out of 3D Text using C#. 1 Answer
Start timer on mouse0 click 1 Answer
How to make UI image in screen space look at a gameobject in world space? 0 Answers