- Home /
Using Object Rotation For Changing the pitch of Sound
Hello! I'm new to Unity and especially for coding but I'm interested in how to realise that the pitch of a sound changes by the rotating of a cube for example.
Answer by metalted · Dec 15, 2021 at 06:55 AM
You might want to check out the following page: https://docs.unity3d.com/ScriptReference/AudioSource-pitch.html . You can alter the example scripts OnGUI function to fit your needs.
We then look up how to get the angle from a gameobject, like on this page: https://answers.unity.com/questions/49095/get-object-rotation-angle.html .
Last thing would be to scale the rotation value (0-180) to the low and high pitch values. This is just a simple formula, which you can find here: https://stats.stackexchange.com/questions/281162/scale-a-number-between-a-range.
Finally we combine everything and end up with the following code:
using UnityEngine;
// A script that plays your chosen song. The pitch starts at 1.0.
// You can increase and decrease the pitch and hear the change
// that is made.
public class AudioExample : MonoBehaviour
{
public float pitchValue = 1.0f;
public AudioClip mySong;
private AudioSource audioSource;
private float low = 0.75f;
private float high = 1.25f;
void Awake()
{
audioSource = GetComponent<AudioSource>();
audioSource.clip = mySong;
audioSource.loop = true;
}
void Update()
{
float angle = Quaternion.Angle(Quaternion.Euler(new Vector3(0,0,0)),transform.rotation);
float pitchValue = (angle / 180f) * (high - low) + low;
audioSource.pitch = pitchValue;
}
}
The pitch will be highest at 180 degrees, lowest at 0.
Answer by Zaeran · Dec 15, 2021 at 06:44 AM
Using a Gameobject variable named 'cube' as an example:
GetComponent<AudioSource>().pitch = cube.transform.eulerAngles.x / 360;
This will set the pitch from 0 - 1 based on the x axis rotation of the cube. You can play with the numbers a little to get the pitch higher than 1, such as dividing by 180 to get a value between 0 - 2