Use AddRelativeTorque() instead of transform.Rotation ()

Using AddRelativeTorque() keeps the code simple and seems to do away with the physics bug. Also acts more realistic in my opinion by adding a rotational torque force instead of trying to brute-force the objects rotation.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{

[SerializeField] float mainThrust = 1f;
[SerializeField] float turnTorque = 1f;
Rigidbody rocketRigidbody;

private void Awake() 
{
    rocketRigidbody =  GetComponent<Rigidbody>();    
}

void Update()
{
    ProcessThrust();
    ProcessRoatation();
}

void ProcessThrust()
{
    if(Input.GetKey(KeyCode.Space))
    {
        rocketRigidbody.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
    }
}

void ProcessRoatation()
{
    if(Input.GetKey(KeyCode.A))
    {
        ApplyRotation(turnTorque);
    }
    if (Input.GetKey(KeyCode.D))
    {
        ApplyRotation(-turnTorque);
    }

}

void ApplyRotation(float rotationThisFrame)
{
    rocketRigidbody.AddRelativeTorque(Vector3.forward * rotationThisFrame * Time.deltaTime);
}

}

1 Like

I had the same idea, but it is much more difficult to control the rocket. I had the idea, that I reset everytime the angular Velocity, when I release the Buttons, with them I rotate the Rocket. So it is much more easier now to control it.

if (Input.GetKeyUp(KeyCode.A) || (Input.GetKeyUp(KeyCode.D)))
{
rb.angularVelocity = Vector3.zero;
}

1 Like

Another method that may be useful for doing this is increasing the angular drag of the rigidbody in the inspector.

Basically equivalent to what is done by setting the angularVelcoity to zero like you have done here is to set that “Angular Drag” (which has to do with how fast the angularVelocity decays - to my understanding), is to set the “Angular Drag” to some infinitely high number such that the angular velocity instantly snaps back to zero when buttons are not pressed. (This second method gives additional control if you want the rotation to overshoot a bit - but not uncontrollably - from the point the player stops pressing the button. By increasing the number.)

Another interesting property that I stumbled across is that you can actually set a maximum angular velocity in code (i.e.; change it from the default value of 7). This is what I have done in the start method below, since I didn’t like how fast my character / rocket was moving if I held the buttons down.

void Start()
{
    playerRigidbody = GetComponent<Rigidbody>();
    playerRigidbody.maxAngularVelocity = 1.5f;
}

It’s useful to know that you can also watch how the velocity is building up in the inspector while you play (see Rigidbody → Info → Angular Velocity):

Correction: What I noted above about the angular drag isn’t quite right actually. Setting angular drag too high will make it so that you can’t even rotate your object :laughing:

1 Like

Privacy & Terms