Search Unity

Getting Animation to work Correctly?

Discussion in 'Scripting' started by CelticKnight, Feb 1, 2015.

  1. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    Hello Guys,

    I have implemented a way of starting/stopping a platform using a collider (in 3D environment) - pretty basic I know - but I have a problem stopping the animation of the "Lift". The code was given in the book "Beginning 3D Game Development" for a continually running platform thusly:

    Code (JavaScript):
    1. if(activateLift == true){
    2.         var weight = Mathf.Cos(Time.time * speed * 2* Mathf.PI) *0.5 + 0.5;
    3.         transform.position = targetA.transform.position * weight + targetB.transform.position * (1 - weight);
    4.         }//-->end if
    So when I stop (or start) the animation it stops it much like "Lap time" on a stopwatch the platform is still moving but it's just not being updated on screen. It seems that Time.time is the culprit here in that it's continually counting up from the start of the game. But I don't know enough about coding or unity to have the animation start or stop dead.

    So to anyone who is willing to help here is a big thankyou in advance.
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Yes, Time.time keeps on updating. So you will need an additional counter to keep track of your lift. Do something like this:
    Code (CSharp):
    1. float liftTimer = 0;
    2.  
    3. void Update() {
    4. if(activateLift == true){
    5.         liftTime+=Time.deltaTime;
    6.         var weight = Mathf.Cos(liftTime * speed * 2* Mathf.PI) *0.5 + 0.5;
    7.         transform.position = targetA.transform.position * weight + targetB.transform.position * (1 - weight);
    8.         }//-->end if
    9. }
     
    CelticKnight likes this.
  3. VisualTech48

    VisualTech48

    Joined:
    Aug 23, 2013
    Posts:
    247
    Since you code in Java, this is the Java version
    Code (JavaScript):
    1. var liftTimer = 0;
    2.  
    3. function Update(){
    4. if(activateLift == true){
    5.   liftTime += Time.deltaTime;
    6.   var weight = Mathf.Cos(liftTime * speed * 2 * Mathf.PI) * 0.5 + 0.5;
    7.   transform.position = targetA.transform.position * weight + targetB.transform.position * (1 - weight);
    8. }
     
    CelticKnight likes this.
  4. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    I was indisposed for the last 2 days the Superbowl not helping matters ;).

    But many, many thanks to both of you for your input! I had a feeling that Time.deltaTime might provide an answer, but, I am very new to Unity and would have never figured out how to go about implementing or scripting it

    So thankyou, thankyou, thankyou it worked a treat :cool:.
     
    Last edited: Feb 3, 2015