【问题标题】:Change light intensity back and forth over time随着时间的推移来回改变光强度
【发布时间】:2018-07-27 14:26:25
【问题描述】:

如何在 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.
    }
}

【问题讨论】:

  • 基本上,您希望在 2 秒内将其从 3.08 更改为 1.0,然后再返回 3.08。来回走动?
  • 是的先生来回。

标签: c# unity3d light


【解决方案1】:

要在两个值之间进行 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);
}

如果您更喜欢使用 duration 而不是 speed 变量来控制光强度,那么最好使用协程函数和 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());
}

【讨论】:

  • 哦,太好了,我什至不知道 mathf 的乒乓球功能我需要再次深入文档
  • @Eddge 是的。过段时间挖掘一些 Unity API 的文档,你会惊讶地发现你不知道存在的函数。 Vector3.Lerp 用得最多,但有些人不知道Mathf.LerpQuaternion.Lerp 也存在。
  • 谢谢先生,工作就像一个魅力。我将使用您的代码来试验值:D
  • 我知道你试图表现出尊重,但你不必称呼别人先生。他们可能和你同龄。不客气!
猜你喜欢
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多