Tilt a spaceship character when moving

Hello guys !

I’m working on a project where the main character is a spaceship.
My goal is to make it slightly tilt in the direction he is moving to. For the moment, I’m trying to do it by applying a rotation with transform.Rotate depending on which direction it is moving. The thing is I have trouble to do it correctly and I feel like there is a much easier way to do it simply by using Unity methods who work with rotation.

Here is what I have so far :

if (movement == e_mov_dir.RIGHT)
        {
            if (prevTranslateX != e_mov_dir.RIGHT)
            {
                if (prevTranslateX == e_mov_dir.LEFT)
                    shipMeshTransform.Rotate(new Vector3(0, 0, 40));
                else
                    shipMeshTransform.Rotate(new Vector3(0, 0, 20));
            }
        }
        if (movement == e_mov_dir.LEFT)
        {
            if (prevTranslateX != e_mov_dir.LEFT)
            {
                if (prevTranslateX == e_mov_dir.RIGHT)
                    shipMeshTransform.Rotate(new Vector3(0, 0, -40));
                else
                    shipMeshTransform.Rotate(new Vector3(0, 0, -20));
            }
        }
        if (movement == e_mov_dir.UP)
        {
            if (prevTranslateZ != e_mov_dir.UP)
            {
                if (prevTranslateZ == e_mov_dir.DOWN)
                    shipMeshTransform.Rotate(new Vector3(40, 0, 0));   
                else
                    shipMeshTransform.Rotate(new Vector3(20, 0, 0));
            }
        }
        if (movement == e_mov_dir.DOWN)
        {
            if (prevTranslateZ != e_mov_dir.DOWN)
            {
                if (prevTranslateZ == e_mov_dir.UP)
                    shipMeshTransform.Rotate(new Vector3(-40, 0, 0));
                else
                    shipMeshTransform.Rotate(new Vector3(-20, 0, 0));
            }
        }

Thanks for your help !

Store the target angles separately, and as absolutes, and then assign the rotation all at once. Something like:

// up at the start of the class
private float pitch = 0f;
private float roll = 0f;

// down in your update
public Update()
{
// your other code

if (movement == e_mov_dir.RIGHT)
    roll = -20;
else  if (movement == e_mov_dir.LEFT)
  roll = 20;

if (movement == e_mov_dir.UP)
  pitch = -20;
if (movement == e_mov_dir.DOWN)
  pitch = 20;

// increase 10.0f to rotate the ship faster, decrease it to rotate slower
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(pitch, 0f, roll), 10.0f * Time.deltaTime);
}
1 Like

Awesome, works for me !

Thanks !