Steering a Spaceship using rigidbody
Hello there,
I spent a lot of time trying to figure this out, but I just can't do it, sigh. To show you what I want to do, I draw this little image, only for you folks.
I want to control the spaceship by directly accessing the engines. Meaning, when I put a force on 0, it rotates to the right, a force on 2 to the left and a force on all 3 of them or on 1 only makes it go forward. Sadly, this doesn't really work, and I am wondering what I am doing wrong, this whole rigidbody thing just doesn't work for me and it's kind of frustrating. Enough of me whining, here comes the code (the part that matters):
function Update(){
if(Input.GetKeyDown("j"))
raiseEngine(0);
if(Input.GetKeyDown("k"))
raiseEngine(1);
if(Input.GetKeyDown("l"))
raiseEngine(2);
if(enginePower0 != 0){
dir = engine[0].transform.forward;
rb.constraints = RigidbodyConstraints.FreezeRotationX;
rb.constraints = RigidbodyConstraints.FreezeRotationZ;
rb.AddForceAtPosition(dir.normalized * enginePower0 * 0.000002, engine[0].transform.position, ForceMode.Force);
rb.constraints = RigidbodyConstraints.None;
}
if(enginePower1 != 0){
dir = engine[1].transform.forward;
rb.AddForce(dir.normalized * enginePower1 * 2, ForceMode.Force);
//rb.constraints = RigidbodyConstraints.None;
}
if(enginePower2 != 0){
dir = engine[2].transform.forward;
rb.constraints = RigidbodyConstraints.FreezeRotationX;
rb.constraints = RigidbodyConstraints.FreezeRotationZ;
rb.AddForceAtPosition(dir.normalized * enginePower2 * 0.000002, engine[2].transform.position, ForceMode.Force);
rb.constraints = RigidbodyConstraints.None;
}
}
function raiseEngine(number: int){
if(number == 0)
enginePower0 +=1;
else if(number == 1)
enginePower1 += 1;
else if(number == 2)
enginePower2 += 1;
}
The whole rigidbody.constrains thing is done because the ship is rotating in any randomly direction it can.
Any help will be truly appreciated, thank you so much in advance!
I think that in your situation, you need to use Rigidbody.AddTorque for turning. You can probably leave things pretty much as they are, but just add some torque on the correct axis (Y?) when you fire engines 0 or 2. If your ship can move freely in 3d space, then you would probably want to use Rigidbody.AddRelativeTorque.
He Ahndrakhul,
Thank you so much! I will try to Addtorque, sounds like a good plan. Could you maybe explain to me what the difference between "AddRelativeForce/Torque" and "AddForce/Torque" is?
Alright, I got it. Everything works good now, with adding torque and stuff. Way better than before. Thank you very much, Ahndrakhul!
Your answer
![](https://koobas.hobune.stream/wayback/20220612075408im_/https://answers.unity.com/themes/thub/images/avi.jpg)