using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PlayerLoop;
public class ChangeShaders : MonoBehaviour
{
private int val;
// Start is called before the first frame update
void Start()
{
//StartCoroutine(EffectSliderChanger());
}
private void Update()
{
gameObject.GetComponent<Renderer>().material.SetFloat("Effect Slider", val);
Mathf.Lerp(-1, 1, Time.deltaTime);
}
/*IEnumerator EffectSliderChanger()
{
gameObject.GetComponent<Renderer>().material.SetFloat("Effect Slider", 1);
}*/
}
我想把效果值在-1和1之间,不停地从-1变成1,当它变成1时,又变成-1,以此类推。
我不确定怎么做,是使用StartCoroutine还是在更新中做。
您可以使用mathf.pingpong
执行此操作
Material material;
// Adjust via Inspector
public float duration = 1;
private void Awake()
{
material = GetComponent<Renderer>().material;
}
void Update()
{
var currentValue = Mathf.Lerp(-1 , 1, Mathf.PingPong(Time.time / duration, 1));
material.SetFloat("Effect Slider", currentValue);
}
或者,您也可以简单地移动范围,如
这将在-1
和1
之间移动,使用pingpon
的结果作为插值因子,在给定的持续时间内在0
和1
之间移动。
或者,您也可以直接移动pingpong
的范围
var currentValue = Mathf.PingPong(Time.time / duration, 2) - 1f;
试试这个(我没有测试过,但应该能用):
public class ChangeShaders : MonoBehaviour
{
private float fromValue = -1f;
private float toValue = 1f;
private float timeStep = 0f;
private float val = 0f;
private void Update()
{
gameObject.GetComponent<Renderer>().material.SetFloat("Effect Slider", val);
val = Mathf.Lerp(fromValue, toValue, timeStep);
timeStep += Time.deltaTime;
// If you want the values to go back and forth faster use the line below instead
// timeStep += 0.2f + Time.deltaTime;
if (timeStep >= 1f) {
float tempVal = fromValue;
toValue = fromValue;
fromValue = tempVal;
timeStep = 0f;
}
}
}