Hello all,
I’m currently working on a flight simulator project just for fun. I’m trying to work on the pitch, yaw, roll, acceleration, and braking, however it’s not working like I planned. I’m trying to make it to where I can pitch up to takeoff from the runway, however it doesn’t let me do that until I’ve gone clear off the runway (currently an elongated cube). I want to be able to pitch up when the plane reaches a certain speed. When I do pitch up after I’ve fallen off the runway, the plane doesn’t go in the direction it faces. It just keeps going forward parallel to the runway. When it loses some speed, it falls down. I want the rigidbody feel of a flight simulator, but I don’t want the plane to fall that drastically after a little bit of flying. Could someone look at my code and tell me what I’m doing wrong?
P.S. It’s just the script, you can throw it on a cube or something in your own project to see what I mean.
using UnityEngine;
using System.Collections;
public class RBPlaneCntrl : MonoBehaviour {
public float thrust; // Magnitude of Velocity
public Rigidbody rb; // Declares Rigidbody
public float MaximumVelocity = 500; // Velocity the plane can reach at max speed.
public float MinimumVelocity = 1; // Velocity the plane can reach at minimum speed.
public float AccIncrement = 2; // Increment by which the plane accelerates & decelerates.
public float pitchTorque = 100; // The force that plane will turn while pitching.
public float rollTorque = 100; // The force that plane will turn while rolling.
public float yawTorque = 100; // The force that plane will turn while yawing.
// For additional inf on YPR, look at this:
// http://www.toymaker.info/Games/assets/images/yawpitchroll.jpg
void Start () { // Initialization
rb = GetComponent<Rigidbody>(); // Sets the rigidbody to the RB component attached to the GameObject.
thrust = 1; // Sets the thrust to 1, otherwise other methods wouldn't work.
}
void Update () { // Updates everything once per frame.
if(Input.GetKey("q") && (thrust <= MaximumVelocity && thrust > MinimumVelocity-1 )) { // Accelerate plane based on conditions given.
thrust += AccIncrement; // Changes thrust by an increment of AccIncrement.
AcceleratePlane(); // Calls the AcceleratePlane function.
}
if (Input.GetKey("e") && (thrust > MinimumVelocity)) { // Decelerate plane based on coordinates given.
thrust -= AccIncrement * 10; // Changes thrust by an increment of AccIncrement times ten.
DeceleratePlane(); // Calls the DeceleratePlane function.
}
PitchPlane();
}
void AcceleratePlane() { // Accelerates the plane forward.
rb.AddRelativeForce(transform.forward * thrust); // Add force to the RB foward * thrust
}
void DeceleratePlane() { // Brakes the plane.
rb.AddRelativeForce(-transform.forward * thrust); // Add neg force to the RB forward * thrust.
}
void PitchPlane() {
float turn = Input.GetAxis("Vertical");
rb.AddTorque(transform.right * pitchTorque * turn * 10);
}
}