I have a cycle and want the cycle bar, having a value range from 0 to 1 and back to 0.
So, currently I use this code
public class DayNightCycle : MonoBehaviour
{
private float currentTime = 0; // current time of the day
private float secondsPerDay = 120; // maximum time per day
private Image cycleBar; // ui bar
private void Start()
{
cycleBar = GetComponent<Image>(); // reference
UpdateCycleBar(); // update the ui
}
private void Update()
{
currentTime += Time.deltaTime; // increase the time
if (currentTime >= secondsPerDay) // day is over?
currentTime = 0; // reset time
UpdateCycleBar(); // update ui
}
private void UpdateCycleBar()
{
cycleBar.rectTransform.localScale = new Vector3(currentTime / secondsPerDay, 1, 1);
}
}
but now I want a behaviour as mentioned by the picture above. How can I increase currentTime
from 0 to 1 and then back to 0?
The problem: My cycle bar should still increase from the left to the right.
The night should last 40% of the maximum time, the other ones 20%.
If you are looking for a way to increase a variable from 0
to 1
then from 1
to 0
, Mathf.PingPong
is the answer. There are many other ways to do this but Mathf.PingPong
is made for tasks like this one.
public float speed = 1.19f;
void Update()
{
//PingPong between 0 and 1
float time = Mathf.PingPong(Time.time * speed, 1);
Debug.Log(time);
}
Do this by Mathf.Sin() function. But you must get absolute value of it. Mathf.abs(mathf.sin()); It will change between 0 to 1 then back to zero. But its not smooth in zero.
Or offset sin function by +1 at the end multiply it by 0.5f to let it back to one again.
float timer = 0;
float cycle = 0;
public float speed = 1;
void Update()
{
timer += Time.deltaTime;
Cycle();
}
void Cycle()
{
cycle = (Mathf.Sin(timer) + 1) * 0.5f;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With