Search Unity

[Solved] GameObject jitter using transform.LookAt

Discussion in 'Scripting' started by Richard_Roth, Jul 19, 2019.

  1. Richard_Roth

    Richard_Roth

    Joined:
    Dec 29, 2014
    Posts:
    64
    I've got a gameObject (health bar) that's childed to a space ship that moves quite rapidly, causing a slight jitter occasionally because the gameObjects transform and scale are constantly being updated in FixedUpdate.

    I know the solution has something to do with Quaternions and interpolation, but I don't quite know how to implement it into my code.

    Here is the script I'm using.
    Code (CSharp):
    1. public class statusBar_configuration : MonoBehaviour
    2. {
    3.     public float scaleDistance;
    4.     //default 0, 0, -1
    5.     public Vector3 transformRotationVertical;
    6.     //default 0,1,0
    7.     public Vector3 transformRotationHorizontal;
    8.     // FixedUpdate is called every fixed frame-rate frame
    9.     void FixedUpdate()
    10.     {
    11.         AlignStatusBar();
    12.     }
    13.  
    14.  
    15.     public void AlignStatusBar()
    16.     {
    17.         try
    18.         {
    19.             //scales gameObject relative to camera distance
    20.             float dist = Vector3.Distance(Camera.main.transform.position, gameObject.transform.position) * scaleDistance;
    21.             gameObject.transform.localScale = Vector3.one * dist;
    22.             //modifies transform relative to camera position
    23.             gameObject.transform.LookAt(transform.position + Camera.main.transform.rotation * transformRotationVertical, Camera.main.transform.rotation * transformRotationHorizontal);
    24.  
    25.         }
    26.         catch
    27.         {
    28.  
    29.         }
    30.     }
    31. }
    32.  
    Object structure and inspector found here.
    https://imgur.com/a/baFnk9k

    Video found here.
    https://vimeo.com/user100950944/review/348931462/1bf711790d
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Try LateUpdate instead of FixedUpdate.

    FixedUpdate is specifically for physics related code, and is called immediately before the physics update. FixedUpdate is called on a regular schedule (default 50 times per second), and is independent of frame rate. There can be several frames or no frames between each FixedUpdate call.

    LateUpdate is called immediately after Update every frame, and is good for code which needs to wait until all other code from Update has ran. It is often used for positioning UI windows in world space above characters, moving the main camera, etc.
     
  3. Richard_Roth

    Richard_Roth

    Joined:
    Dec 29, 2014
    Posts:
    64
    Thanks, your answer lead me to more research and I found the answer. Camera update needs to be the same update as the lookat function. I changed the camera update to FixedUpdate, which solved the problem.