c# - 随着时间的推移来回改变光强度

标签 c# unity-game-engine light

如何在 2 秒后将光强度值从 3.08 更改回 1.0。我在代码中添加了注释以获取更多信息

public class Point_LightG : MonoBehaviour {

    public Light point_light;
    float timer;

    // Use this for initialization
    void Start () {
        point_light = GetComponent<Light>();
    }

    // Update is called once per frame
    void Update () {
        timer -= Time.deltaTime;
        lights();
    }

    public void lights()
    {
        if (timer <= 0)
        {
            point_light.intensity = Mathf.Lerp(1.0f, 3.08f, Time.time);
            timer = 2f;
        }

        // so after my light intensity reach 3.08 I need it to gradually change back to 1.0 after 2 seconds.
    }
}

最佳答案

要在两个值之间进行 lerp,只需将 Mathf.PingPongMathf.Lerp 结合使用,并提供 lerp 发生的速度。

public Light point_light;
public float speed = 0.36f;

float intensity1 = 3.08f;
float intensity2 = 1.0f;


void Start()
{
    point_light = GetComponent<Light>();
}

void Update()
{
    //PingPong between 0 and 1
    float time = Mathf.PingPong(Time.time * speed, 1);
    point_light.intensity = Mathf.Lerp(intensity1, intensity2, time);
}

如果您更喜欢使用持续时间而不是速度变量来控制光强度,那么最好使用协程函数和 Mathf.Lerp 函数带有一个简单的计时器。然后可以在 x 秒内完成 lerp。

IEnumerator LerpLightRepeat()
{
    while (true)
    {
        //Lerp to intensity1
        yield return LerpLight(point_light, intensity1, 2f);
        //Lerp to intensity2
        yield return LerpLight(point_light, intensity2, 2f);
    }
}

IEnumerator LerpLight(Light targetLight, float toIntensity, float duration)
{
    float currentIntensity = targetLight.intensity;

    float counter = 0;
    while (counter < duration)
    {
        counter += Time.deltaTime;
        targetLight.intensity = Mathf.Lerp(currentIntensity, toIntensity, counter / duration);
        yield return null;
    }
}

使用

public Light point_light;

float intensity1 = 3.08f;
float intensity2 = 1.0f;

void Start()
{
    point_light = GetComponent<Light>();
    StartCoroutine(LerpLightRepeat());
}

关于c# - 随着时间的推移来回改变光强度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51560049/

相关文章:

c# - Polly 验证单元测试中 httpclient 超时/重试的次数

c# - 使 WPF Tabcontrol 标题垂直堆叠

ios - 从 Unity iOS 项目创建 pod

unity-game-engine - 带有标记标签的 Unity UI 文本 - "String too long for TextMeshGenerator"

ios - ARKit + SceneKit : Object lags when adding to the scene

android - 如何获取光传感器的具体值

c# - 我可以使用 DOCX 库将 DOCX 文件另存为 HTML 吗?

c# - @Html.Action 正在从部分 View 镜像我的网站,而不引用布局页面?

unity-game-engine - 无法在 Unity 中登录 Fabric,收到 "Network error!"消息

graphics - Threejs 中的 LED 灯带