public class FlightControls : MonoBehaviour {
public KeyCode
accelerate = KeyCode.LeftShift, // Key used to accelerate
decelerate = KeyCode.LeftControl; // Key used to decelerate
public float
maxSpeed = 1000000, // Maximum speed
minSpeed = 0; // Minimum speed
public Camera
playerView; // The main camera
GameObject cameraTarget; // The point that the camera looks at (just above the plane)
float
currentSpeed = 0; // The current speed
void Start()
{
cameraTarget = new GameObject(); // Creates a new pivot point
playerView = Camera.main; // Sets the current camera
Cursor.visible = false; // Hides the cursor
if(GetComponent<Rigidbody>() == null) // If there is no rigidbody
{
gameObject.AddComponent<Rigidbody>(); // Create a rigidbody
GetComponent<Rigidbody>().useGravity = false; // Don't use gravity
}
cameraTarget.transform.parent = transform; // Sets the pivot point as a child to the plane
}
void Update()
{
Controls();
CameraControls();
}
void Controls()
{
if(Input.GetKey(accelerate) && currentSpeed < maxSpeed) // If the accelerate key is pressed and the plane can accelerate
{
currentSpeed++; // Accelerate
}
if (Input.GetKey(decelerate) && currentSpeed > minSpeed) // If the decelerate key is pressed and the plane can decelerate
{
currentSpeed--; // Decelerate
}
transform.Rotate(new Vector3(Input.GetAxis("Mouse Y"), Input.GetAxis("Horizontal"), -Input.GetAxis("Mouse X")));
/*
* Rotation breakdown:
* - X rotation is the pitch (up/down)
* - Y rotation is the yaw (left/right)
* - Z rotation is the roll (tilt left/right)
*/
GetComponent<Rigidbody>().velocity = transform.forward * currentSpeed; // Moves the plane forward at the current speed
}
void CameraControls()
{
playerView.transform.LookAt(cameraTarget.transform); // Looks at the pivot point
cameraTarget.transform.position = transform.position + (transform.up * 2); // Sets the pivot point 2 units above the plane
playerView.transform.position = transform.position - (transform.forward * 10) + (transform.up * 2); // Sets the camera 10 units behind and 2 units above the plane
}
}
Attach this script to a cube of size (3, 0.3, 3) and you have yourself a primitive flying object