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

Question Unable to rotate transform's Z value when also using LookAt on that Transform

Discussion in 'Scripting' started by NewSystemGames, Jun 5, 2023.

  1. NewSystemGames

    NewSystemGames

    Joined:
    May 23, 2017
    Posts:
    303
    I'm using the below code to have the transform look at the camera, the below function updates the X and Y rotation value of my transform:
    Code (CSharp):
    1. transform.LookAt(transform.position + cam.transform.forward, cam.transform.up);
    I want to also, while having the transform looking at the camera to rotate on the Z axis using the below code
    Code (CSharp):
    1. transform.Rotate(Vector3.forward * speed * Time.deltaTime);
    Result is the transform looks at the camera but the Z rotation is being overwritten, rotating very little and resetting

    I also tried using the below code to achieve look at camera which still overwrites my Rotate code
    Code (CSharp):
    1.         Vector3 targetDirection = cam.transform.position - transform.position;
    2.         targetDirection.y = 0f;
    3.         transform.rotation = Quaternion.LookRotation(targetDirection, Vector3.up);
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    I think this is just a situation where you need to make another game object that's a child of the transform being controlled with LookRotation, and rotate that child instead.
     
    NewSystemGames likes this.
  3. NewSystemGames

    NewSystemGames

    Joined:
    May 23, 2017
    Posts:
    303
    That does it, thank you
     
  4. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,913
    The other solution, which you were working towards, is to use the existing "up" in the lookAt:
    transform.LookAt( ... , transform.up);
    . As you noted, LookAt always resets the z rotation. It has to. The 2nd input says how to reset it. The most common input, Vector3.up, resets to world up.