Posts Tagged ‘ unity

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.

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.

Read more

Shotput 0.1

I always enjoyed the old Konami Track & Field games, so I thought I’d try to work out the controls and do a shotput game in a similar vein with physics.  This demo just has the “Power” part of the controls (the part controlled by jamming two buttons alternately) and the scene set up (with primitives).  The demo is done in the free version of Unity and requires the Unity plugin.

Controls:

Power: A/S (alternating)

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

I’m going to keep all the controls separate (power, angle, fire) and have a manager for all the different events to tie various controls together. That way I could use the power controls again for, say, the 100m dash. The next step will be to add the controls to direct the angle of the shot.