Search Unity

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

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

  1. CyberInteractiveLLC

    CyberInteractiveLLC

    Joined:
    May 23, 2017
    Posts:
    307
    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:
    7,819
    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.
     
    CyberInteractiveLLC likes this.
  3. CyberInteractiveLLC

    CyberInteractiveLLC

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

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,996
    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.