thibaud-d
3/1/2017 - 11:00 AM

Simple flight controls (no physics/collision) useful for inspecting or demoing a scene. Add to camera and you are set. [ = ] to accelerate;

Simple flight controls (no physics/collision) useful for inspecting or demoing a scene. Add to camera and you are set. [ = ] to accelerate; [ - ] to decelerate; SPACE to stop and start.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class SimpleFlightControls : MonoBehaviour {

	[Header("Parameters")]
	[Tooltip("Current/Default Speed")]
	public float speed = 1.0f;
	public float accel = 0.5f;
	public bool invertPitch=true;

	[Header("Keyboard config")]
	public KeyCode keyToAccelerate = KeyCode.Equals;
	public KeyCode keyToDecelerate = KeyCode.Minus;
	public KeyCode keyToStop = KeyCode.Space;

	[Header("Variables")]

	[Tooltip("Rotation around vertical axis (look left or right)")]
	public float yaw   = 0f;
	[Tooltip("Rotation around x axis (look up or down)")]
	public float pitch = 0f;

	private float defaultSpeed = 1.0f;

	void Start(){
		defaultSpeed = speed;
	}

	void Update () {

		if (Application.isPlaying) {
			float delta = Time.deltaTime;

			yaw += Input.GetAxis ("Horizontal");
			pitch += Input.GetAxis ("Vertical");
			speed += Input.GetKey (keyToAccelerate) ? accel * delta : 0f;
			speed -= Input.GetKey (keyToDecelerate) ? accel * delta : 0f;
			if (Input.GetKeyUp (keyToStop)) {
				if (speed != 0f) {
					speed = 0f;
					print ("Stop");
				} else if (speed == 0f) {
					print ("Resume");
					speed = defaultSpeed;
				}
			}
			transform.position += transform.forward * speed * Time.deltaTime;
		}

		transform.localEulerAngles = new Vector3 (invertPitch?-pitch:pitch, yaw, 0f);

	}

}