Unity 实现相机视角慢慢变黑的效果(VR)

一、在相机下新建一个Canvas,添加Image 和CanvasGroup 组件

Unity 实现相机视角慢慢变黑的效果(VR)_第1张图片

二、通过代码控制CanvasGroup 组件中Alpha值

以下函数要放在Update中执行。

第一种写法(判断条件为Alpha 0-1的值)

    private float Alpha;
    private float AlphaSpeed = 1.5f; //Alpha值渐变的时间
    /// 
    /// 控制Alpha值增加
    /// 
    /// 
    public void AlphaControl(GameObject _mask)
    {
        if (_mask != null)
        {
            _mask.SetActive(true);

            Alpha += Time.deltaTime * 1 / AlphaSpeed;
            _mask.GetComponent().alpha = Alpha;
           
            if (Alpha >= 0.95f) playAnimation = PlayAnimation.EnterGame;

        }
    }

第二种写法(判断条件为持续时间)

    /// 
    /// 屏幕遮罩
    /// 
    public CanvasGroup screenMask; 
     /// 
    /// 遮罩的Alpha
    /// 
    private float maskAlpha;
    /// 
    /// 遮罩的Alpha持续时间
    /// 
    private float maskAlphaDuration = 5f;
     /// 
    /// 游戏结束画面逐渐变黑并退出游戏场景
    /// 
    private void GameOver()
    {
        if (isGameOver)
        {
            maskAlpha += Time.deltaTime;
            screenMask.alpha = maskAlpha / maskAlphaDuration;
            if (maskAlpha >= maskAlphaDuration)
            {
                maskAlpha = 0;
#if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
#else
                Application.Quit();
#endif
            }
        }
    }

三、 通过Image组件实现相机的遮罩效果

注意:如果CanvasGroup和Image同时存在,需将CanvasGroup的Alpha值改为1,再进行控制Image的Alpha值。

     /// 
    /// 屏幕遮罩
    /// 
    public Image screenMask; 
     /// 
    /// 遮罩的Alpha
    /// 
    private float maskAlpha;
    /// 
    /// 遮罩的Alpha持续时间
    /// 
    private float maskAlphaDuration = 5f;    
    /// 
    /// 游戏结束画面逐渐变黑并退出游戏场景
    /// 
    private void GameOver()
    {
        if (isGameOver)
        {
            var r = screenMask.color.r;
            var g = screenMask.color.g;
            var b = screenMask.color.b;

            maskAlpha += Time.deltaTime;
            screenMask.color = new Color(r, g, b, maskAlpha / maskAlphaDuration);
            if (maskAlpha >= maskAlphaDuration)
            {
                maskAlpha = 0;
#if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
#else
                Application.Quit();
#endif
            }
        }
    }

你可能感兴趣的:(Unity3DVR开发,Unity,UGUI,c#,unity)