Unity Increase a value and then decrease it (DayNightCycle)

I have a loop and need a loop line having a range of values ​​from 0 to 1 and back to 0.

enter image description here

So, I am currently using 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 need the behavior mentioned above. How to increase currentTimefrom 0 to 1, and then return to 0?

Problem: my loop line should increase left to right.

The night should last 40% of the maximum time, the remaining 20%.

+4
source share
3 answers

0 1, 1 0, Mathf.PingPong - . , Mathf.PingPong , .

public float speed = 1.19f;

void Update()
{
    //PingPong between 0 and 1
    float time = Mathf.PingPong(Time.time * speed, 1);
    Debug.Log(time);
}
+7

Mathf.Sin(). . Mathf.abs(mathf.sin()); 0 1, . .

sin +1 0.5f, .

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;
}
+1

0 1, -1 1.

-1, deltaTime, , , 1, reset -1. ...

float timer = -1;

void Update()
{
  timer += Time.deltaTime;

  if(timer >= 1)
  {
    timer = -1;
  }
    Cycle();
}

void Cycle()
{
    //Do Your Cycle
//-1 is left night, 0 is middle day, 1 is right night
}
+1

Source: https://habr.com/ru/post/1683323/


All Articles