Files
CopterSimulator/Unity/Assets/Scripts/Motor.cs
T

52 lines
1.0 KiB
C#
Raw Normal View History

2025-05-13 03:30:23 +03:00
using UnityEngine;
using System.Collections;
public class Motor : MonoBehaviour {
public GameObject rotor;
public float maxRpm = 3000;
public float speed;
public float minPitch = 0.8f;
public float maxPitch = 1.2f;
public AudioSource soundSource;
private float[] speedHistory;
int historyId = 0;
void Start(){
speedHistory = new float[15];
for (int i = 0; i < speedHistory.Length; ++i) {
speedHistory[i] = 0;
}
}
void Update(){
if (soundSource != null) {
speedHistory[historyId] = speed;
historyId = (historyId + 1) % speedHistory.Length;
float smoothSpeed = 0;
for (int i = 0; i < speedHistory.Length; ++i) {
smoothSpeed += speedHistory[i];
}
smoothSpeed = smoothSpeed / (float)speedHistory.Length;
float pitch = (smoothSpeed / maxRpm) * (maxPitch - minPitch) + minPitch;
soundSource.pitch = pitch;
if(soundSource.isPlaying && speed < 5){
soundSource.Stop();
}
if(!soundSource.isPlaying && speed >=5){
soundSource.Play();
}
}
}
}