Search Unity

Way to move sprite position from code on each keyframe change

Discussion in '2D' started by lecksfrawen, Nov 27, 2013.

  1. lecksfrawen

    lecksfrawen

    Joined:
    Nov 22, 2013
    Posts:
    2
    Hi. I want to do the following:
    - On every keyframe change I move the sprite position to a new position.

    I have the following:
    - An animation of 12 FPS with 26 keyframes, each with a different sprite.
    - A Vector3 array with 26 elements, each with a position for it's corresponding keyframe.

    Is there an event/callback on Unity 4.3 that can help me achieve this?
    If not, how could I go about this?

    I've tried a couple of workarounds:
    - A simple frame counter, each time the frame counter reached 5, I incremented a frameIndex
    - Each time the sprite name changes, increment the frameIndex.
    Neither worked since the position keeps getting out of sync with my sprite:

    Before Unity4.3, with the 2D framework Orthello2D, I could do this with delegate OnAnimationFrame. This way, every time the frame changed on my animation I could move it's position.
     
  2. lecksfrawen

    lecksfrawen

    Joined:
    Nov 22, 2013
    Posts:
    2
    Well, I found another approach, I post my solution here in case anyone is curious:

    Code (csharp):
    1.    
    2. void Update ()
    3. {
    4.     // First I get the current sprite name
    5.     string spriteName = aSpriteRenderer.sprite.name;
    6.  
    7.     // I changed the sprite names to be:  pu_0, pu_1, pu_2, pu_3 ... pu_25
    8.     // Now I can just use the number at the end as my array index, so I extract it.
    9.     string[] nameAndIndex = spriteName.Split ( '_' );
    10.     int frameIndex = int.Parse( nameAndIndex[1] );
    11.  
    12.     // Finally I change the position of an empty gameObject that's parent of my sprite based on the frame index
    13.     aSpriteContainer.transform.position = animPosArr[ frameIndex ];
    14. }
    15.  
    This way I can change the position reliably.