随着时间的推移缩放游戏对象 [英] Scale GameObject over time

查看:34
本文介绍了随着时间的推移缩放游戏对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的圆柱类代码

 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);
    }
}

推荐答案

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

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;
}

用法:

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

Will scale GameObject within 20 seconds:

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

这篇关于随着时间的推移缩放游戏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆