[英]Change width parameter of Trail Renderer with audio spectrum C# Script in Unity
我正在尝试找到一种方法,可以通过音频文件中的音频频谱动态更改轨迹渲染器的宽度参数。 我已经成功地能够更改游戏对象的比例,但是无法更改轨迹渲染器本身的实际宽度参数。 这是用于动态更改音频频谱使用比例的代码。 任何帮助或建议,将不胜感激! 谢谢
使用音频频谱更改音阶的代码:
using UnityEngine;
using System.Collections;
public class trailTest : MonoBehaviour {
public float width = 5.0f;
public bool useCurve = true;
private TrailRenderer tr;
public int numberOfObjects = 1;
void Start ()
{
tr = GetComponent<TrailRenderer> ();
tr.material = new Material (Shader.Find ("Sprites/Default"));
}
void Update ()
{
AnimationCurve curve = new AnimationCurve ();
if (useCurve) {
curve.AddKey (0.0f, 0.0f);
curve.AddKey (1.0f, 1.0f);
} else {
curve.AddKey (0.0f, 1.0f);
curve.AddKey (1.0f, 1.0f);
}
float [] spectrum = AudioListener.GetSpectrumData (1024, 0, FFTWindow.Hamming);
for (int i = 0; i < numberOfObjects; i++) {
Vector3 previousScale = tr.transform.localScale;
previousScale.y = Mathf.Lerp (previousScale.y, spectrum [i] * 80, Time.deltaTime * 30);
tr.transform.localScale = previousScale;
}
}
}
解决了:
using UnityEngine;
using System.Collections;
public class trailTest : MonoBehaviour
{
private TrailRenderer trailRenderer;
public GameObject [] trailerbaby;
public int numberOfObjects = 1;
void Start ()
{
trailRenderer = gameObject.GetComponent<TrailRenderer> ();
float startWidth = trailRenderer.startWidth;
float endWidth = trailRenderer.endWidth;
trailRenderer.startWidth = 1f;
trailRenderer.endWidth = 1f;
Debug.Log ("Start width: " + startWidth + '\t' + "End width: " + endWidth);
trailerbaby = GameObject.FindGameObjectsWithTag ("trailerbaby");
}
void Update ()
{
trailRenderer = gameObject.GetComponent<TrailRenderer> ();
float startWidth = trailRenderer.startWidth;
float endWidth = trailRenderer.endWidth;
Debug.Log ("Start width: " + startWidth + '\t' + "End width: " + endWidth);
float [] spectrum = AudioListener.GetSpectrumData (1024, 0, FFTWindow.Hamming);
for (int i = 0; i < numberOfObjects; i++) {
//Vector3 previousPosition = trailerbaby [i].transform.localPosition;
trailRenderer.startWidth = Mathf.Lerp (trailRenderer.startWidth, spectrum [i] * 2000, Time.deltaTime * 13000 * 10);
trailRenderer.endWidth = Mathf.Lerp (trailRenderer.startWidth, spectrum [i] * 2000, Time.deltaTime * 13000 * 10);
//previousPosition.y = Mathf.Lerp (previousPosition.y, spectrum [i] * 2000, Time.deltaTime * 13000);
//trailerbaby [i].transform.localPosition = previousPosition;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.