Que*_*n3r 4 c# unity-game-engine
我有一个循环并想要循环条,其值范围从0到1并返回0.
所以,目前我使用这个代码
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但现在我想要一个如上图所示的行为.如何currentTime从0增加到1然后再回到0?
问题:我的循环条应该仍然从左向右增加.
夜晚应该持续最长时间的40%,其他的20%.
如果你正在寻找一种方式来增加一个变量来自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);
}
Run Code Online (Sandbox Code Playgroud)