随着时间的推移缩放游戏对象

Ken*_*isi 0 c# unity-game-engine

我统一制作了一个测试游戏,当我单击按钮时,它会生成一个从工厂类创建的圆柱体。我试图做到这一点,以便当我创建圆柱体时,它的高度会在接下来的 20 秒内缩小。我发现的一些方法很难转化为我正在做的事情。如果您能引导我走向正确的方向,我将非常感激。

这是我的圆柱体类代码

 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pro*_*mer 6

这可以通过协程函数中的Time.deltaTimeand来完成。Vector3.Lerp类似于随时间旋转游戏对象随时间移动游戏对象问题。稍微修改一下就可以做到这一点。

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;
}
Run Code Online (Sandbox Code Playgroud)

用法

将在 20 秒内缩放游戏对象:

StartCoroutine(scaleOverTime(cylinder.transform, new Vector3(0, 0, 90), 20f));
Run Code Online (Sandbox Code Playgroud)