Expanding and Contracting Planets not working

Hi Everyone,

Just trying to get my planet to expand and then contract, its expanding properly to the large size then just flashing between the small and large scale.

var bigScale : Vector3 = Vector3(3,3,3); var smallScale : Vector3 = Vector3(1,1,1);

if(shrink)
{
    currentPlanet.transform.localScale = Vector3.Lerp (transform.localScale, bigScale, Time.time*0.5);  
    if(currentPlanet.transform.localScale == bigScale)
    {
        shrink = false;
    }
}
else
{
    currentPlanet.transform.localScale = Vector3.Lerp (transform.localScale, smallScale, Time.time*0.5);  
    if(currentPlanet.transform.localScale == smallScale)
    {
        shrink = true;
    }
}

I know its something simple just can't get it to work right.

Thanks

Chris

Hi, I believe it is because you are using Time.time in your lerp. Have a look at eric5h5's answer on this unityAnswers page: link It is very informative on this issue. The last paragraph describes why Time.time does not work, the rest has some solutions.

Hey,

Just replace Time.time with Time.deltaTime. I tested the code and it works well, alternating between shrinking and expanding the scale of a sphere.

Here's the code:

if(shrink)
{
    currentPlanet.transform.localScale = Vector3.Lerp (transform.localScale, bigScale, Time.deltaTime * 5);  

    if(currentPlanet.transform.localScale == bigScale)
    {
        shrink = false;
    }
}
else
{
    currentPlanet.transform.localScale = Vector3.Lerp (transform.localScale, smallScale, Time.deltaTime * 5);

    if(currentPlanet.transform.localScale == smallScale)
    {
        shrink = true;
    }
}

On a side note, I also sped it up to 5 instead of 0.5 so you can see the change faster. When set to 0.5 you'll get a very long period of time where the planet seems to expand/shrink VERY slowly. This is because it's waiting to reach exactly smallScale/bigScale.

Instead I would suggest waiting for a smaller number, for example:

if(shrink)
{
    currentPlanet.transform.localScale = Vector3.Lerp (transform.localScale, bigScale, Time.deltaTime * 0.5);  

    if(currentPlanet.transform.localScale.x > bigScale.x * 0.9)
    {
        shrink = false;
    }
}
else
{
    currentPlanet.transform.localScale = Vector3.Lerp (transform.localScale, smallScale, Time.deltaTime * 0.5);

    if(currentPlanet.transform.localScale.x < smallScale.x * 1.1)
    {
        shrink = true;
    }
}

Note the if conditions are waiting for a number near the target. This way you'll skip the part where the planet keeps scaling at ~0.00001 per second. Also, I only compared localScale.x, as there's no need to compare the rest since the planet is expanding the same in all axis.