Flight Sim help
I was wondering if there is a tutorial on creating something like this: https://www.reddit.com/r/Unity3D/comments/5gamip/tried_my_hand_at_making_a_space_plane_controller/
I don't really care about the model, I just wanna know how to code the speed, smooth turning and using your mouse to control the plane.
If anyone could send me a tutorial or teach me that, it would be awsome. Thanks for reading!
Answer by Konomira · Dec 12, 2016 at 12:50 AM
using UnityEngine;
using System.Collections;
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
Thank you for the help, but I'm getting 2 errors
The referenced script on this Behavior is missing!
The referenced script on this Behavior (GameCube) is missing!
$$anonymous$$ake sure the script is called FlightControls.cs
Gee thanks! It's working now. Time to make textures and models :D