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 set single axis of rotation?

Discussion in 'Scripting' started by S_Rockjaw, Sep 3, 2020.

  1. S_Rockjaw

    S_Rockjaw

    Joined:
    Aug 19, 2020
    Posts:
    2
    I think the solution to this is probably simple but I'm new at this.

    I'm making an endless driving/shooting game. I have a car with a turret on the roof. The turret is a child of the car. I'm trying to write some code to control the rotation of the turret using the right joystick. I only want to set the y-axis. I want the turret to inherit the x and z rotation from the car.

    My camera is locked pointing toward z. So in terms of setting the y rotation, it could be relative to the camera or the world space. I think it would be the same in this case. 0 degrees is forward, 90 degrees is right, etc...

    Here some temporary code I was using to control the turret. It's ok on flat terrain but it overrides the x and the z rotation as well so when the car rides on slopes the turret remains level, clipping into the roof of the car.

    Code (CSharp):
    1.         Vector3 lookDirection = new Vector3(Input.GetAxisRaw("R_Horizontal"), 0, Input.GetAxisRaw("R_Vertical"));
    2.         Turret.rotation = Quaternion.LookRotation(lookDirection);

    What's the right way to do this?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    You could project the look direction onto the desired plane before using it as the look rotation. Also LookRotation has a second parameter specifying the "up" direction, which seems relevant here. Otherwise it uses world up (Vector3.up) which will make it off-kilter from the parent.

    Code (CSharp):
    1.         Vector3 lookDirection = new Vector3(Input.GetAxisRaw("R_Horizontal"), 0, Input.GetAxisRaw("R_Vertical"));
    2.         Vector3 projectedLookDirection = Vector3.ProjectOnPlane(lookDirection, Turret.parent.up);
    3.         Turret.rotation = Quaternion.LookRotation(projectedLookDirection, Turret.parent.up);
     
    Last edited: Sep 3, 2020
  3. S_Rockjaw

    S_Rockjaw

    Joined:
    Aug 19, 2020
    Posts:
    2
    That did it. Thank you.