Search Unity

Rotating Z Axis while always facing the camera?

Discussion in 'Getting Started' started by Maple-Senpai, Feb 28, 2019.

  1. Maple-Senpai

    Maple-Senpai

    Joined:
    Oct 2, 2018
    Posts:
    14
    Hello, I'm new to the Unity community and I'm having some problems with my game code.

    So, I'm creating a 3D underwater game for my capstone project at school and I'm having an issue in rotating my player in the z axis while its always facing the camera. I'm using a 2D image as my player and I already did the part where it will always face the camera but when I want to rotate / spin it in the z-axis its not working.

    Here's the code:

    Code (CSharp):
    1. public Camera mainCam;
    2.  
    3. void LateUpdate()
    4.     {
    5.         transform.Rotate(0, 0, Time.deltaTime*50);
    6.         transform.LookAt(transform.position + mainCam.transform.rotation * Vector3.forward,
    7.         mainCam.transform.rotation * Vector3.up);
    8.     }
    With this, the player still does always face the camera but the rotation is not working. Any help would be appreciated. Thank you :)
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    That's because transform.LookAt sets the rotation to something else.

    There are lots of ways to solve this, but I think maybe the easiest and most useful for you would be to separate the two problems into two different GameObjects:

    1. Put your player inside an empty GameObject (at the same position). Call that PlayerContainer.
    2. Put a script on the PlayerContainer that does the LookAt in LateUpdate to face the camera (i.e., the above script without line 5).
    3. Put a script in the Player that rotates around Z (i.e., the above script without line 6-7).
     
  3. Maple-Senpai

    Maple-Senpai

    Joined:
    Oct 2, 2018
    Posts:
    14

    Thanks for replying but I did what you said and the player is going really weird now. Whenever I move my mouse the player accelerates so fast forward or backward. I'm sorry if I explained that poorly.