Unity implements the effect of the camera perspective slowly turning black (VR)

1. Create a new Canvas under the camera and add Image and CanvasGroup components.

2. Control the Alpha value in the CanvasGroup component through code

The following functions should be executed in Update.

The first way of writing (the judgment condition is the value of Alpha 0-1)

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

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

        }
    }

The second way of writing (the judgment condition is duration)

    /// <summary>
    /// 屏幕遮罩
    /// </summary>
    public CanvasGroup screenMask; 
     /// <summary>
    /// 遮罩的Alpha
    /// </summary>
    private float maskAlpha;
    /// <summary>
    /// 遮罩的Alpha持续时间
    /// </summary>
    private float maskAlphaDuration = 5f;
     /// <summary>
    /// 游戏结束画面逐渐变黑并退出游戏场景
    /// </summary>
    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
            }
        }
    }

3. Implement camera masking effect through Image component

Note: IfCanvasGroup and Image exist at the same time, you need to change the Alpha value of CanvasGroup to 1, and then control the Alpha value of Image.

     /// <summary>
    /// 屏幕遮罩
    /// </summary>
    public Image screenMask; 
     /// <summary>
    /// 遮罩的Alpha
    /// </summary>
    private float maskAlpha;
    /// <summary>
    /// 遮罩的Alpha持续时间
    /// </summary>
    private float maskAlphaDuration = 5f;    
    /// <summary>
    /// 游戏结束画面逐渐变黑并退出游戏场景
    /// </summary>
    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
            }
        }
    }

Guess you like

Origin blog.csdn.net/U3DCoder/article/details/123345323