Head Bob Script. Can someone explain this script?

I want to edit this script, but I don’t really understand it. What I want is to play a footstep sound when the headbob reaches its lowest point.
Can someone help me understand this script. Maybe put comments or if you know how I will add in the sound at the right point. Please teach a man to fish! :stuck_out_tongue:

public class HeadBob : MonoBehaviour {

	private float timer = 0.0f;
	public float bobbingSpeed = 0.18f;
	public float bobbingAmount = 0.2f;
	public float midpoint = 2.0f;

	public float count = 0;
	float waveslice;
	float horizontal;
	float vertical;
	Vector3 cSharpConversion;
	void Update () {

		waveslice = 0.0f;
		horizontal = Input.GetAxis("Horizontal");
		vertical = Input.GetAxis("Vertical");
		cSharpConversion = transform.localPosition;
		if(transform.localPosition.y < 1.9f)
		if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0) {
			timer = 0.0f;
		else {
			waveslice = Mathf.Sin(timer);
			timer = timer + bobbingSpeed;
			if (timer > Mathf.PI * 2) {
				timer = timer - (Mathf.PI * 2);

		if (waveslice != 0) {
			float translateChange = waveslice * bobbingAmount;
			float totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
			totalAxes = Mathf.Clamp (totalAxes, 0.0f, 1.0f);
			translateChange = totalAxes * translateChange;
			cSharpConversion.y = midpoint + translateChange;
		else {
			cSharpConversion.y = midpoint;
		transform.localPosition = cSharpConversion;

This code is using a sine wave to determine where the head should be in its bounce (see line 28). Look at a sine wave graph (below) - “waveslice” will follow this curve as the timer is incremented. So, if you’re looking at the graph, the x axis is “timer” and the y-value of the curve at any given time is “waveslice”.

In line 35 you check to see if waveslice is not zero, or if the point you’re on on the sine wave is not at zero. Within that if statement, check to see if waveslice is -1. If it is, you’ve reached the lowest point on the sine wave and should play your footstep.

The problem with this is that waveslice may not reach -1 each time. Because you’re relying on a timer, which is incremented by bobbingSpeed, you can’t guarantee that it’ll always make waveslice hit 1. So, you may want to do the following:

if(waveslice <= -.95 && !transform.parent.GetComponent().audioIsPlaying())
    //play audio

You can fiddle with the -.95 if it’s not working… -.9 for example may call the footbeat a little earlier but would have a better chance of working than -.95.

alt text