Power Control script
Following is the code for the power control script. I’ve annotated it more with an eye towards beginning/intermediate Unity users than anything else. At the least, bits of it won’t make sense without some grasp of C#/.NET conventions.
using UnityEngine; using System.Collections; public class TrackAndFieldPower : MonoBehaviour { //The flag for whether control is enabled is marked as //NonSerialized so it is public, but will not show up in the inspector. [System.NonSerialized] public bool canControl = true; // These are the variables we want exposed to the inspector so they can be //tweaked once everything is in place. public float powerStep = 0.1f; public float powerMax = 1.0f; public float powerDrop = 0.1f; public float inputTimeout = 0.1f; public float dropTimeout = 0.5f; private float _power = 0.0f; private float accumulatedDropTime = 0.0f; // Flag for cycling back and forth between accepting button 0 and button 1. private bool button0 = true; private bool dropMode = true; public void Start() { StartCoroutine (AcceptPower ()); } public void OnGUI () { GUILayout.Label ("Power: " + this.power); } // Coroutine for handling power control. Control falls through when canControl // becomes false (which we aren't doing anything with just yet). IEnumerator AcceptPower () { while (canControl) { // First check to see if we should be dropping the power because the // player stopped entering input. if (dropMode) { _power = Mathf.Clamp(power - powerDrop, 0, powerMax); } // If the player entered the correct input, reset the power drain timeout // and add some power. if ((button0 && Input.GetButtonDown("Power0")) || (!button0 && Input.GetButtonDown("Power1"))) { dropMode = false; accumulatedDropTime = 0.0f; _power = Mathf.Clamp(power + powerStep, 0, powerMax); button0 = !button0; // Yield control to the engine and wait for the input timeout // (if we accept whenever the engine is ready, humans won't be // able to keep up) before returning to the loop. yield return new WaitForSeconds (inputTimeout); } else { // If the player hasn't entered input, start counting until we // hit the power drain threshhold. accumulatedDropTime += Time.deltaTime; if (accumulatedDropTime >= dropTimeout) { dropMode = true; } // In this case, we don't need any extra timeout to allow for human // input, we want to go right back into this loop as soon as the engine will let us. yield return 0; } } } // Power is read-only public float power { get { return this._power; } } }
No comments yet.