Search Unity

How to set location of object relative to another object without it jittering/stuttering/jerking

Discussion in 'Scripting' started by HopelessHyena, Sep 30, 2015.

  1. HopelessHyena

    HopelessHyena

    Joined:
    May 26, 2015
    Posts:
    18
    Hi Everyone,

    I have an AI character which has a nav mesh agent component to it, which moves around the scene and attacks the player.

    I need to have another object look like it's attached to the AI character as it moves around; but for various reasons I cannot parent it.

    The problem is, calling object.transform.position = aICharacterNavAgent.transform.position; on every update results in jerky movement.

    How can I get around this jerky movement without parenting it?

    Thanks in advance!
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Shouldn't do, have you tried LateUpdate?

    Otherwise you can abuse Lerp like this to create a smoothing effect.

    Code (CSharp):
    1. transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * speed);
    The effect should be somewhat like a spring, pulling the object a little closer to target each frame. And the pull will be stronger the further away the object is from target.
     
  3. HopelessHyena

    HopelessHyena

    Joined:
    May 26, 2015
    Posts:
    18
    I have tried using LateUpdate, and it did not work - it had exactly the same effect as a regular update.
    It may be worth mentioning that the object which I am repositioning has a rigid body component, and is set to kinematic. (I am therefore using object.MovePosition(...))

    Wouldn't using Lerp be redundant since this is supposed to update every frame?
     
  4. HopelessHyena

    HopelessHyena

    Joined:
    May 26, 2015
    Posts:
    18
    Any other suggestions as to what I could do?