using UnityEngine;
namespace Crosstales.Common.Audio
{
/// Simple spectrum visualizer.
public class SpectrumVisualizer : MonoBehaviour
{
#region Variables
///FFT-analyzer with the spectrum data.
[Tooltip("FFT-analyzer with the spectrum data.")] public FFTAnalyzer Analyzer;
///Prefab for the frequency representation.
[Tooltip("Prefab for the frequency representation.")] public GameObject VisualPrefab;
///Width per prefab.
[Tooltip("Width per prefab.")] public float Width = 0.075f;
///Gain-power for the frequency.
[Tooltip("Gain-power for the frequency.")] public float Gain = 70f;
///Frequency band from left-to-right (default: true).
[Tooltip("Frequency band from left-to-right (default: true).")] public bool LeftToRight = true;
///Opacity of the material of the prefab (default: 1).
[Tooltip("Opacity of the material of the prefab (default: 1).")] [Range(0f, 1f)] public float Opacity = 1f;
private Transform tf;
private Transform[] visualTransforms;
private Vector3 visualPos = Vector3.zero;
private int samplesPerChannel;
#endregion
#region MonoBehaviour methods
private void Start()
{
tf = transform;
samplesPerChannel = Analyzer.Samples.Length / 2;
visualTransforms = new Transform[samplesPerChannel];
for (int ii = 0; ii < samplesPerChannel; ii++)
{
//cut the upper frequencies >11000Hz
GameObject tempCube;
if (LeftToRight)
{
Vector3 position = tf.position;
tempCube = Instantiate(VisualPrefab, new Vector3(position.x + ii * Width, position.y, position.z), Quaternion.identity);
}
else
{
Vector3 position = tf.position;
tempCube = Instantiate(VisualPrefab, new Vector3(position.x - ii * Width, position.y, position.z), Quaternion.identity);
}
tempCube.GetComponent().material.color = Util.BaseHelper.HSVToRGB(360f / samplesPerChannel * ii, 1f, 1f, Opacity);
visualTransforms[ii] = tempCube.GetComponent();
visualTransforms[ii].parent = tf;
}
}
private void Update()
{
for (int ii = 0; ii < visualTransforms.Length; ii++)
{
visualPos.Set(Width, Analyzer.Samples[ii] * Gain, Width);
visualTransforms[ii].localScale = visualPos;
}
}
#endregion
}
}
// © 2015-2020 crosstales LLC (https://www.crosstales.com)