使用Unity中的音频谱C#脚本更改Trail Renderer的宽度参数

时间:2017-12-10 18:31:15

标签: c# unity3d audio

我正在尝试使用音频文件中的音频频谱来动态更改跟踪渲染器的宽度参数。我已经成功地改变了游戏对象的比例,但没有改变跟踪渲染器本身的实际宽度参数。以下是用于动态更改使用音频频谱的规模的代码。任何帮助或建议将不胜感激!感谢

使用音频谱改变音阶的代码:

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;

      }
   }
 }

1 个答案:

答案 0 :(得分:0)

解决:

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;

        }

    }
}
相关问题