其他分享
首页 > 其他分享> > 随机更改相机背景颜色

随机更改相机背景颜色

作者:互联网

我正在尝试在随机选择的两种颜色之间平滑更改相机的背景颜色.我已经实现了,但是随后我开始注意到,每当选择一种新颜色时都会出现闪光.我已经在link上上传了有关该问题的视频.这是我当前正在使用的脚本:

public Color color1;
public Color color2;

float time;
float time2;
float transition;

int firstColor = 0;


void Update()
{
    if (firstColor == 0)
    {
        color1 = Random.ColorHSV(Random.value, Random.value);
        color2 = Random.ColorHSV(Random.value, Random.value);

        firstColor = 1;
    }

    Camera.main.backgroundColor = Color.Lerp(color2, color1, transition);

    time += Time.deltaTime;
    time2 += Time.deltaTime;
    transition = time2 / 5;

    if (time > 5)
    {
        color2 = color1;
        color1 = Random.ColorHSV(Random.value, Random.value);

        time = 0;
        time2 = 0;
    }
}

很感谢任何形式的帮助.

解决方法:

您需要使用协程进行此操作.然后,您可以轻松地编程当前过渡结束后何时更改新颜色.任何您需要加班的事情,都应该始终考虑使用协程.它消除了很多布尔变量和混乱的需求.

您可以在没有布尔变量的协程函数中等待,但不能在诸如Update函数的void函数中等待.您已经在使用Time.deltaTime和Lerp函数,因此您知道自己在做一半.这是执行此操作的正确方法:

//2 seconds within each transition/Can change from the Editor
public float transitionTimeInSec = 2f;

private bool changingColor = false;

private Color color1;
private Color color2;


void Start()
{
    StartCoroutine(beginToChangeColor());
}

IEnumerator beginToChangeColor()
{
    Camera cam = Camera.main;
    color1 = Random.ColorHSV(Random.value, Random.value);
    color2 = Random.ColorHSV(Random.value, Random.value);

    while (true)
    {
        //Lerp Color and wait here until that's done
        yield return lerpColor(cam, color1, color2, transitionTimeInSec);

        //Generate new color
        color1 = cam.backgroundColor;
        color2 = Random.ColorHSV(Random.value, Random.value);
    }
}

IEnumerator lerpColor(Camera targetCamera, Color fromColor, Color toColor, float duration)
{
    if (changingColor)
    {
        yield break;
    }
    changingColor = true;
    float counter = 0;

    while (counter < duration)
    {
        counter += Time.deltaTime;

        float colorTime = counter / duration;
        Debug.Log(colorTime);

        //Change color
        targetCamera.backgroundColor = Color.Lerp(fromColor, toColor, counter / duration);
        //Wait for a frame
        yield return null;
    }
    changingColor = false;
}

标签:smoothing,unity3d,colors,background-color,c
来源: https://codeday.me/bug/20191110/2015257.html