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 Does transform.LookAt() override z rotation?

Discussion in 'Scripting' started by s200025, Jun 12, 2023.

  1. s200025

    s200025

    Joined:
    May 13, 2022
    Posts:
    1
    I'm currently trying to make almost a snake like simulation where a number of cubes are following each other with slight delays. Everything was working as well as the mimicking of the Z rotation of the target causing a spiral until I added transform.LookAt(target). Now the subsequent blocks do not turn in z axis no matter what the target does. here is a bit of the code, excuse the huge mess. :)

    Code (CSharp):
    1. Quaternion currentRotation = transform.rotation;
    2.         Quaternion targetRotationWithoutY = Quaternion.Euler(currentRotation.eulerAngles.x, targetRotation.eulerAngles.y, targetRotation.eulerAngles.z);
    3.         Quaternion targetRotationWithoutYZ = Quaternion.Euler(targetRotationWithoutY.eulerAngles.x, 0f, 0f);
    4.         desiredRotation = Quaternion.Lerp(currentRotation, targetRotationWithoutYZ, rotationSpeed * Time.deltaTime);
    5.  
    6.         //this makes the objects rotate in the z axis
    7.         float desiredZRotation = Mathf.LerpAngle(currentRotation.eulerAngles.z, targetRotationWithoutY.eulerAngles.z, spiralSpeed * Time.deltaTime);
    8.         desiredRotation.eulerAngles = new Vector3(desiredRotation.eulerAngles.x, desiredRotation.eulerAngles.y, desiredZRotation);
    9.  
    10.         transform.rotation = desiredRotation;
    11.  
    12.         // Look at the target
    13.         transform.LookAt(target.transform.position);
    14.     }
    I've messed with the spiral speed but that doesn't make a difference.
     
    Last edited: Jun 13, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    There's a solution for the huge mess!!

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    The magic you're looking for is the optional second argument to the
    Transform.LookAt()
    method.

    Hie thee to the Transform documentation to see what I mean!