Search Unity

Animate from current position to center of screen

Discussion in 'Editor & General Support' started by LittleCodingFox, Jul 2, 2015.

  1. LittleCodingFox

    LittleCodingFox

    Joined:
    Jul 2, 2015
    Posts:
    11
    Is there any way to animate a UI element zooming in from its position to the center of the screen? The position may vary so I'm not sure how to do this. I read about the LateUpdate() trick but I don't think it'll work for this.
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    This is untested code:
    Code (CSharp):
    1. Vector3 startPos;
    2. Vector3 endPos;
    3.  
    4. float startScale = 0; // change these as you like
    5. float endScale = 1;
    6.  
    7. float scaleDuration = 1; // seconds
    8.  
    9. float interp; // short for interpolation - look it up if you aren't familiar, it's one of the most useful math tricks in programming
    10.  
    11. void Start()
    12. {
    13.     startPos = transform.position;
    14.     endPos = new Vector3(0, 0, 0); // or wherever you want it
    15.     interp = 0;
    16. }
    17.  
    18. void Update()
    19. {
    20.     if (interp < 1)
    21.     {
    22.         interp += Time.deltaTime / duration;
    23.         if (interp > 1) interp = 1;
    24.     }
    25.     transform.position = startPos * (1 - interp) + endPos * interp;
    26.     transform.localScale = new Vector3(1, 1, 1) * (startScale * (1 - interp) + endScale * interp);
    27. }