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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Adjusting Roll and Pitch with Velocity

Discussion in 'Scripting' started by vanzandtlg, Apr 30, 2022.

  1. vanzandtlg

    vanzandtlg

    Joined:
    Oct 8, 2020
    Posts:
    5
    1. I'd like the roll and pitch of my submarine to react to changing direction. Going back-and-forth changes the pitch; side-to-side changes the roll.

    2. I have the following code that lerps between a x and z rotation as a function of x and z velocity

    Code (CSharp):
    1.         xVelocity = rigidbody.velocity.x;
    2.         yVelocity = rigidbody.velocity.y;
    3.         zVelocity = rigidbody.velocity.z;
    4.  
    5.         maxXVelocityPercentage = Mathf.Abs(xVelocity / maxXVelocity);
    6.         maxYVelocityPercentage = Mathf.Abs(yVelocity / maxYVelocity);
    7.         maxZVelocityPercentage = Mathf.Abs(zVelocity / maxZVelocity);
    8.  
    9.         activeXAngle = Mathf.Lerp(0, maxXAngle, maxXVelocityPercentage);
    10.         activeZAngle = Mathf.Lerp(0, maxZAngle, maxZVelocityPercentage);
    11.  
    12.  
    13.         if (xVelocity > 0)
    14.             activeXAngle = -activeXAngle;
    15.         if (zVelocity > 0)
    16.             activeZAngle = -activeZAngle;
    17.  
    18.         transform.localEulerAngles = new Vector3(activeZAngle, 0f, activeXAngle);
    3. Works great when the sub is straight in the scene, however, if not, then the sub starts reading any movement as contributing towards the z velocity and giving me weird rotations.



    4. Is there a way to localize velocity? Or a better way of doing what I'm trying to do?

    Thanks!
     
    Last edited: Apr 30, 2022
  2. Cameron_SM

    Cameron_SM

    Joined:
    Jun 1, 2009
    Posts:
    915
    Please see the forum sticky post about using code tags.
     
    Bunny83 likes this.
  3. vanzandtlg

    vanzandtlg

    Joined:
    Oct 8, 2020
    Posts:
    5
    Sorry about that. Should be fixed.