How do I conserve momentum
Hi I am trying to make a basic flight sim in and am currently working on the first person camera aspect of it. This feels more or less like a real flight sim as long as I hold down the forward button but as soon as I let go I stop. How do I make it so I conserve momentum?
public class CameraController : MonoBehaviour
{
public Rigidbody rb;
private float speed = 25.0f;
private float rotationSpeed = 120.0f;
private float pitchSpeed = 60.0f;
//private bool brake = false;
private void Start() {
rb.GetComponent<Rigidbody>();
}
void Update () {
float translation = Input.GetAxis("Vertical") * speed; //sets the movement params
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
float pitch = Input.GetAxis("Pitch") * pitchSpeed;
translation *= Time.deltaTime;
rotation *= Time.deltaTime;//normalizing per framerate
pitch *= Time.deltaTime;
//Vector3 movement = new Vector3(0, pitch, translation);
//rb.velocity = movement;
transform.Translate(0, 0, translation);
transform.Rotate(pitch, 0, rotation);
}
}
Answer by lgarczyn · Dec 26, 2019 at 01:36 AM
The problem is that you are not actually using the rigidbody, but simply forcing the rigidbody at specific positions. You should avoid moving a gameobject containing a rigidbody using transform.
The lines
translation *= Time.deltaTime;
rotation *= Time.deltaTime;//normalizing per framerate
pitch *= Time.deltaTime;
//Vector3 movement = new Vector3(0, pitch, translation);
//rb.velocity = movement;
transform.Translate(0, 0, translation);
transform.Rotate(pitch, 0, rotation);
can be replaced by
rb.velocity = translation ;
rb.angularVelocity = new Vector2(pitch, 0f, rotation);
And that's all. Make sure that your rigidbody is not kinematic.
After trying your suggestion of changing this rb.velocity = new Vector3(0f, 0f, throttle); rb.angularVelocity = new Vector3(pitch, 0f, rotation); I found that I could only move forward on one axis, and the pitch and roll of the "plane" were behaving oddly as well. When I rolled it was no longer flat as it should have been and pitch just did odd stuff I can't really describe. I am trying to understand how these rigidbodys work, but I am not getting it so far.