2017-08-09 83 views
0

可視化從0與值範圍內的圖像條爲1,並返回到0 I增加從0到1的值,並且因此,現在的值得到了它的邏輯減少它回0在Unity

private Image cycleBar; 
private float currentTime = 0; 
private float cycleDuration = 5; 

private void Start() 
{ 
    cycleBar = GetComponent<Image>(); 
    UpdateCycleBar(); 
} 

private void Update() // TimeHandler 
{ 
    currentTime = Mathf.PingPong(Time.time * 1/cycleDuration, 1); // handle the time 
    UpdateCycleBar(); 
} 

private void UpdateCycleBar() 
{ 
    // the missing part 
} 

。我怎麼能想象它像這個例子在這裏

enter image description here

當到達值1,該酒吧就移動到右側的「零號」。之後,它只是重新在左側復位。

+1

難道你需要做0-1-0嗎?我會建議做0-.5-1或0-1-2。 – ryeMoss

+0

以及代碼,重要的是從0到1並返回0.當使用UI時,我可以使用-1到0到1。 – Question3r

+1

如果你想要Time.time *(1/cycleDuration),我想你需要添加更多的括號來強制操作順序。或者你可以把* 1放在一起。因爲這將是相同的Time.time/cycleDuration –

回答

1

您可以嘗試這種方法。但是,如果您想從黃昏初始化它,請不要忘記調用Initialize(float value, TimeMod mod)方法。

using System; 
using UnityEngine; 
using UnityEngine.UI; 

public class CycleBar : MonoBehaviour 
{ 
    [SerializeField] 
    private Image cycleBar; 

    private TimeMod currentMod = TimeMod.AM; 

    public void Initialize(float value, TimeMod mod) 
    { 
     currentMod = mod; 
     cycleBar.fillAmount = GetProgressbarValue(value); 
    } 

    public void UpdateValue(float value) 
    { 
     CheckTimeMod(value); 
     cycleBar.fillAmount = GetProgressbarValue(value); 
    } 

    private void CheckTimeMod(float value) 
    { 
     if (Mathf.Abs(value - 1) < 0.01f) 
     { 
      currentMod = TimeMod.PM; 
     } 

     if (Mathf.Abs(value) < 0.01f) 
     { 
      currentMod = TimeMod.AM; 
     } 
    } 

    private float GetProgressbarValue(float value) 
    { 
     switch (currentMod) 
     { 
      case TimeMod.AM: 
       return value/2; 
      case TimeMod.PM: 
       return 0.5f + Mathf.Abs(value-1)/2; 
      default: 
       throw new ArgumentOutOfRangeException("currentMod", currentMod, null); 
     } 
    } 

    public enum TimeMod 
    { 
     AM, 
     PM 
    } 
} 

和控制器:

using UnityEngine; 

public class Controller : MonoBehaviour 
{ 
    [SerializeField] 
    private CycleBar cycleBar; 

    private void Update() // TimeHandler 
    { 
     var value = Mathf.PingPong(Time.time, 1); // handle the time 
     cycleBar.UpdateValue(value); 
    } 
} 

但如果可能的話,使用更簡單的方式與範圍[-1;1]。例如,如果它可以幫助你,馬克請這個帖子作爲正確答案,你可以使用滑塊從UnityEngine.UI

enter image description here

0

您可以在UI中創建新圖像,然後在2D調整大小模式下將其大小調整爲完整狀態。現在您可以在代碼中將X從零擴展到1。