Posts Tagged ‘ games

Shotput, pt. 2: Angle controls

So we have a way to control the power of our shotput shot.  Another integral component is being able to control the angle.

Controls: Hold space to increase angle, release to fire.

[WP_UnityObject src=”http://www.francisfernandez.com/unity/shotput_0_3.unity3d”/]

using UnityEngine;
using System.Collections;

public class TrackAndFieldAngle : MonoBehaviour {
    public delegate void FireControl (float angle);

    [System.NonSerialized]
    public bool canControl = true;

    public FireControl fireControl;
    private float _angle = 0.0f;
    public float maxAngle = 90.0f;
    public float angleStep = 0.01f;

    // Update is called once per frame
    void Update () {
        if (canControl && Input.GetButtonDown ("Angle")) {
            StartCoroutine (raiseAngle ());
        }
    }

    private IEnumerator raiseAngle () {
        while (canControl && Input.GetButton ("Angle")) {
            _angle = Mathf.Clamp (_angle + angleStep, 0, maxAngle);
            yield return null;
        }
        canControl = false;
        // I use a delegate here to notify interested parties when space has been released and is ready to fire.
        this.fireControl (_angle);
    }

    // angle is read-only
    public float angle {
        get {
            return this._angle;
        }
    }
}

I may go back and rework it so the script is not reliant on Update to operate.  Some items of note, though:

the coroutine returns null rather than 0, per this blog post by AngryAnt,

and C# delegates are a really nice way to do notifications.