This question has probably been asked and answered previously, if so, please provide a reference then we can delete this repeat.
The player will be flying a helicopter. I want to test their ability to keep the helicopter at a specific elevation. I guess the best way would be to have a box collider at the designated test position (in the air). Then “somehow” measure how long the player stays within the collider.
#pragma strict
public var elevation : float = 1000.0;
public var threshold : float = 100.0; // how far they can be off the elevation;
private var timer = 0.0;
function Update() {
if (Mathf.Abs(transform.position.y - elevation) <= threshold) {
timer += Time.deltaTime;
}
else {
timer = 0.0;
}
}
Just keep track of when they enter the collider, and once they’ve not exited it for long enough, success:
public class LocationMonitor : MonoBehaviour {
public float requiredTime = 5f;
float enteredAt = Mathf.infinity;
public delegate void EmptyCallback();
public event EmptyCallback leftEarly;
public event EmptyCallback stayedLongEnough;
public void Reset() {
enabled = true;
enteredAt = Mathf.infinity;
}
void Update() {
if ( Time.time - enteredAt > requiredTime ) {
if ( null != stayedLongEnough ) stayedLongEnough();
enabled = false;
enteredAt = Mathf.infinity;
}
}
void OnTriggerEnter(Collider other) {
enteredAt = Time.time;
}
void OnTriggerStay(Collider other) {
if ( enteredAt == Mathf.infinity ) enteredAt = Time.time;
}
void OnTriggerExit(Collider other) {
if ( Time.time - enteredAt < requiredTime ) {
if ( null != leftEarly ) leftEarly();
}
enteredAt = Mathf.infinity;
}
}
public class GameController : MonoBehaviour {
public LocationMonitor monitor;
void Start() {
monitor.stayedLongEnough += Success;
monitor.leftEarly += Failure;
}
void Success() { Debug.Log("Success"); }
void Failure() { Debug.Log("Failure"); }
}
Typed freehand. Hopefully not too many errors.
You’ll need to either be sure the heli is the only collider that can touch the monitor (using physics layers), or do some object checks in the OnTriggerX functions, but this should be reasonable for testing.