我有一个汽车在道路上行驶的动画,我正在尝试通过“音频源”组件调整引擎声音的音高。问题是每次我在统一编辑器中运行应用程序时,音高值都会飙升,并且在播放之间不一致。
这用于C#和Unity3d。我试图基于最近的三个帧来平均音高,并将音高值限制在1到3之间。当我平均音高时,然后确保它在maxDifference阈值之内以抵抗已经出现的尖峰。动画不是基于根运动的,所以我不能使用“动画速度”字段。为了解决这个问题,我正在使用当前帧的X和Z位置以及输入到距离公式中的最后一个帧来计算一帧的行进距离。然后,我将该值乘以缩放数字来确定我的音高值应该接近什么。可以通过编辑器更改该值,而我最常用的值为12。
public float scaler;
[Range(0, 0.7f)]
public float maxDifference;
public Animator anim;
public AudioSource audiosource;
Vector3 lastPos;
float lastPitch;
float lastPitch2;
float lastPitch3;
var position = transform.position;
float deltaPosition = Mathf.Abs(Mathf.Sqrt(Mathf.Pow((lastPos.z - position.z), 2) + Mathf.Pow((lastPos.x - position.x), 2)));
audiosource.pitch = deltaPosition * scaler + 1;
if (audiosource.pitch < 1)
{
audiosource.pitch = 1;
}
if (Mathf.Abs(audiosource.pitch - (lastPitch + lastPitch2 + lastPitch3) / 3f) > maxDifference
&& !carStart)
{
audiosource.pitch = (lastPitch + lastPitch2 + lastPitch3) / 3f;
}
if (audiosource.pitch > 3f)
audiosource.pitch = 3f;
lastPos = position;
lastPitch3 = lastPitch2;
lastPitch2 = lastPitch;
lastPitch = audiosource.pitch;
我期望音高值保持一致,但是每次运行时,音高值都会每次更改。这些值还会不断增加。
答案 0 :(得分:2)
当当前音高与尾随平均线相距太远时,应将其固定在离尾随平均线一定距离的位置,而不要将其精确设置为尾随平均线。
为简化起见,您可以使用Mathf.Clamp
:
audiosource.pitch = Mathf.Clamp(deltaPosition * scaler + 1, 1f, 3f);
float runningAverage = (lastPitch + lastPitch2 + lastPitch3) / 3f;
if (!carStart)
{
audiosource.pitch = Mathf.Clamp(audiosource.pitch,
runningAverage - maxDifference,
runningAverage + maxDifference);
}
lastPos = this.transform.position;
lastPitch3 = lastPitch2;
lastPitch2 = lastPitch;
lastPitch = audiosource.pitch;