Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to lock roll axis

Discussion in 'Scripting' started by SquareBunnyBoy, Jul 13, 2021.

  1. SquareBunnyBoy

    SquareBunnyBoy

    Joined:
    Feb 16, 2020
    Posts:
    27
    Good day, all!

    Maybe some can give me some help here, please?

    I'm working on flying vehicle controller with physics and I encounter one problem. While using addRelativeTorque to yaw and pitch axes ship also rotating by roll axis at some point.

    So here's my simple code:

    Code (CSharp):
    1.     void LateUpdate()
    2.     {
    3.         float mouseH = Input.GetAxis("Mouse X");
    4.         float mouseV = Input.GetAxis("Mouse Y");
    5.         float hRotation = mouseH * rotationSpeed * Time.deltaTime;
    6.         float vRotation = mouseV * rotationSpeed * Time.deltaTime;
    7.            
    8.         if (InvertY == true) {
    9.             vRotation = -vRotation;
    10.         }  
    11.    
    12.         m_Rigidbody.AddRelativeTorque(Vector3.up * hRotation);
    13.         m_Rigidbody.AddRelativeTorque(Vector3.right * vRotation);
    Can I somehow substract Vector3.forward maybe? Or how else can I lock one axis?

    Thanks!
     
  2. SquareBunnyBoy

    SquareBunnyBoy

    Joined:
    Feb 16, 2020
    Posts:
    27
    Okay.. I figured this out. Not sure if it's a right way to do it, but.. If someone will encounter same problem:

    Code (CSharp):
    1.    
    2. public class ShipController : MonoBehaviour
    3. {
    4.     private float xRot;
    5.     private float yRot;
    6.  
    7. void LateUpdate()
    8.     {    
    9.         xRot = transform.rotation.eulerAngles.x;
    10.         yRot = transform.rotation.eulerAngles.y;
    11.      
    12.         transform.rotation = Quaternion.Euler(xRot, yRot, 0);
    13.  
    14.        m_Rigidbody.AddRelativeTorque(Vector3.up * hRotation);
    15.        m_Rigidbody.AddRelativeTorque(Vector3.right * vRotation);
    16.     }
    17. }
    And after transform.rotation you can addTorque to x and y axes.