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 Bind AnimtionCurve to control the local position of the gam object

Discussion in 'Scripting' started by Korveen, May 22, 2020.

  1. Korveen

    Korveen

    Joined:
    Jan 24, 2015
    Posts:
    12
    Hello!
    I am unable to bind AnimationCurve to a local object transform.
    If you do something like that
    Code (CSharp):
    1.  
    2.     public AnimationCurve animCurve;
    3.     public GameObject target;
    4.     float curveTimer = 0f;
    5.  
    6.     // (1, 0, 0) – x
    7.     // (0, 1, 0) – y
    8.     // (0, 0, 1) – z
    9.     public Vector3 vector = new Vector3(0, 1, 0);
    10.  
    11.     void Update()
    12.     {
    13.  
    14.         curveTimer += Time.deltaTime;
    15.         if (curveTimer > 2)
    16.             curveTimer = 0;
    17.  
    18.         float curveAmount = animCurve.Evaluate(curveTimer);
    19.         target.transform.localPosition = vector * curveAmount;
    20.     }
    21.  
    Everything moves as it should
    *gif1*
    1.gif
    BUT if the object is locally rotated, then it does not move quite as it should.
    *gif2*
    2.gif
    As I understand it, need to use Vector3.up (forward or right depending on which axis).
    But it works the same way and nothing changes. Ithink need to somehow use the direction
    How do I snap an AnimationCurve so that the curve controls the position of the object, like this:
    *gif3*
    3.gif
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    I think you're maybe looking for something like this:
    Code (CSharp):
    1.     public Vector3 vector;
    2.    
    3.     void Start() {
    4.        vector = transform.right;
    5.     }
    6.  
    7.     void Update()
    8.     {
    9.  
    10.         curveTimer += Time.deltaTime;
    11.         if (curveTimer > 2)
    12.             curveTimer = 0;
    13.         float curveAmount = animCurve.Evaluate(curveTimer);
    14.         target.transform.localPosition = vector * curveAmount;
    15.     }
     
  3. Korveen

    Korveen

    Joined:
    Jan 24, 2015
    Posts:
    12
    Wow, I didn’t even think of such a simple solution, lol. Probably just tired. Thanks, It works