- Home /
How to use AddForce and AddTorque to steer my plane through checkpoints?
So I'm making a flight simulator sort of thing but instead of using input from the keyboard I'm trying to make it run on autopilot and fly through checkpoints that I set. I want it to follow the laws of physics so I'll be adding lift, thrust, drag and other variables to make it as life-like as possible. One important thing is that instead of just moving the plane from one coordinate to another I want it to tilt its body left and right when changing direction and the nose of the plane up and down when moving up and down. I've attached a rigidbody and so far this is the code I've got.
public float thrust = 50.0f;
float bias = 0.96f;
private Rigidbody planebody;
public Transform target;
Vector3 dir;
private void Start()
{
planebody = GetComponent<Rigidbody>();
}
void Update () {
Vector3 moveCamTo = transform.position - transform.forward * 10.0f + Vector3.up * 5.0f;
Camera.main.transform.position = Camera.main.transform.position * bias + moveCamTo * (1.0f - bias);
Camera.main.transform.LookAt(transform.position + transform.forward * 30.0f);
//So we don't go through the terrain
float terrainheight = Terrain.activeTerrain.SampleHeight(transform.position);
if (terrainheight > transform.position.y)
{
transform.position = new Vector3(transform.position.x, terrainheight, transform.position.z);
}
}
private void FixedUpdate()
{
dir = target.position - transform.position;
planebody.AddForce(dir);
}
All this does is just take the plane to the target. What I need is the following: for example if the coordinates of the plane are 0,0,0 and the coordinates of the target are 20,30,40, I need the plane to move forward while tilting its nose up to gain height (till the height is equal to the target height) and tilt it's body till its x and z also correspond to the target coordinates. I'll be adding the variables I mentioned so when the plane tilts its nose up for example its speed will decrease because of the increased drag and so forth. Here's the problem. If I just add torque the plane spins around an axis randomly, so I'm trying to figure out how to add torque gradually for example until the nose of the plane tilts up 45 degrees and either continue like that till it reaches the target height or tilt back down to 0 degrees and go forwards if it's already at the target height. Same goes for left/right movement, I need the plane body to tilt up to a certain angle (can't be a large angle - needs to be smooth) and continue staying at that tilted angle whilst moving forwards till it's in sync with the target and then stabilize and fly through the target. One last thing - the movements should happen at the same time so instead of just going up then turning left, I need it to go up and turn left at the same time so it's more like the addition of those two vectors. I really appreciate any help you could give me. Thanks in advance.