Implementing snake-like 2D controls and behavior

Hi, I’m totally new to Unity, and I’m trying to get the hang of it by creating a simple snake clone. So the controls I’m after are:

  • Each fixed time frame, snake advances a fixed distance in the direction it’s currently looking,
  • left key changes the direction by -90 degrees around the z-axis,
  • right key changes it by +90 degrees.

I’ve got some code that sort of does that, but occasionally it makes 2 turns after a key is pressed instead of 1. Any ideas how I might fix this are much appreciated!

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
	int ticks = 0;
	int tickThreshold = 30;
	float stepSize = 1.0f;
	Vector3 nextDirectionChange = Vector3.zero;
	
	void Start () {
		transform.forward = Vector3.right;
	}
	
	void FixedUpdate () {
		this.ticks++;
		if (this.ticks > this.tickThreshold) {
			transform.Rotate(this.nextDirectionChange);
			transform.position += transform.forward * stepSize;
			this.ticks = 0;
			this.nextDirectionChange = Vector3.zero;
		}

		if (Input.GetKey(KeyCode.LeftArrow)) {
			this.nextDirectionChange = Vector3.left * 90;
		}
		if (Input.GetKey(KeyCode.RightArrow)) {
			this.nextDirectionChange = Vector3.right * 90;
		}
	}
}

Use GetKeyUp/Down instead