Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

c# - Scale GameObject over time

I made a test game in unity that makes it so when I click on a button, it spawns a cylinder created from a factory class. I'm trying to make it so when I create the cylinder, its height shrinks over the next 20 seconds. Some methods I found are difficult to translate into what I'm doing. If you could lead me to the right direction, I'd very much appreciate it.

Here's my code for the cylinder class

 public class Cylinder : Shape
{
    public Cylinder()
    {
    GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
        cylinder.transform.position = new Vector3(3, 0, 0);
        cylinder.transform.localScale = new Vector3(1.0f, Random.Range(1, 2)-1*Time.deltaTime, 1.0f);

        cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
        Destroy(cylinder, 30.0f);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be done with the Time.deltaTime and Vector3.Lerp in a coroutine function. Similar to Rotate GameObject over time and Move GameObject over time questions. Modified it a little bit to do just this.

bool isScaling = false;

IEnumerator scaleOverTime(Transform objectToScale, Vector3 toScale, float duration)
{
    //Make sure there is only one instance of this function running
    if (isScaling)
    {
        yield break; ///exit if this is still running
    }
    isScaling = true;

    float counter = 0;

    //Get the current scale of the object to be moved
    Vector3 startScaleSize = objectToScale.localScale;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        objectToScale.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
        yield return null;
    }

    isScaling = false;
}

USAGE:

Will scale GameObject within 20 seconds:

StartCoroutine(scaleOverTime(cylinder.transform, new Vector3(0, 0, 90), 20f));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...