Bootstrap

麦田物语学习笔记:场景切换淡入淡出和动态UI显示

基本流程

        人物在切换场景有些僵硬,所以增加淡入淡出效果

1.代码思路

        (1)核心原理是控制Fade Panel中的CanvasGroup中的Alpha值的大小来实现淡入淡出的效果

        (2)用协程去表示变黑或变透明

        (3)人物输入被阻拦的情况下,人物却还在移动,这个问题需要解决

2.代码实现

        在TransitionManager中去获取相应变量,并实现相应协程

private CanvasGroup fadeCanvasGroup;

private bool isFade;

private void OnTransitionEvent(string sceneToGo, Vector3 positionToGo)
{
    if(!isFade)
        StartCoroutine(Transition(sceneToGo, positionToGo));
}

private IEnumerator Transition(string sceneName, Vector3 targetPosition)
{
    //呼叫卸载场景之前要做的事
    EventHandler.CallBeforeSceneUnloadEvent();

    yield return Fade(1);

    yield return SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene());

    yield return LoadSceneSetActive(sceneName);

    //移动人物坐标
    EventHandler.CallMoveToPosition(targetPosition);

    yield return Fade(0);

    //呼叫加载场景之后的事件
    EventHandler.CallAfterSceneLoadedEvent();
}

private IEnumerator Fade(float targetAlpha)
{ 
    isFade = true;

    fadeCanvasGroup.blocksRaycasts = true;//控制玩家在加载的过程中无法点击

    float speed = Mathf.Abs(fadeCanvasGroup.alpha - targetAlpha) / Settings.fadeDuration;

    while (!Mathf.Approximately(fadeCanvasGroup.alpha, targetAlpha))//因为判断浮点型相等不易判断,所以取近似就行了
    {
        fadeCanvasGroup.alpha = Mathf.MoveTowards(fadeCanvasGroup.alpha, targetAlpha, speed * Time.deltaTime);
        yield return null;
    }

    fadeCanvasGroup.blocksRaycasts = false;

    isFade = false;
}

 新增Settings中的变量

public const float fadeDuration = 0.8f;

修正Player在加载过程的动画问题 

private void Update()
{
    if(!inputDisable)
        PlayerInput();
    else
        isMoving = false;
    SwitchAnimation();
}

private void FixedUpdate()
{
    if(!inputDisable)
        Movement();
}

最终效果

 

;