0

I am trying to make an object scale from zero to it's normal size when I instantiate it, so it will look like it popped to the screen.

So when the object start I get it's normal size then update it to zero, and then in update I am scaling it.

This is my code:

void Start()
{
    normalScale = transform.localScale;
    transform.localScale *= 0.1f;
}
void Update()
{
    transform.localScale = Vector3.Lerp(transform.localScale * 0.1f, transform.localScale, 5f * Time.deltaTime);
    // destroy item
    if (transform.localScale == normalScale)
    {
        transform.localScale = transform.localScale * 0.1f;
    }
}

Thank you.

4

3 回答 3

1

有了这个,你总是从它的当前规模改变,当然你上次更新改变了

transform.localScale = Vector3.Lerp(transform.localScale * 0.1f, transform.localScale, 5f * Time.deltaTime);

您需要做的是在更新函数之外创建两个 Vector3,一个用于起始大小,一个用于最终大小

Vector3 start = Vector3.zero;
Vector3 end = new Vector3(1,1,1);

您还需要一个计时器:

浮动 lerpTime = 0;

总之你得到

transform.localScale = Vector3.Lerp(start, end, lerpTime);
lerpTime += Time.deltaTime // times whatever multiplier you want for the speed
于 2016-09-30T14:08:22.103 回答
1

您的代码有几个问题可能会导致问题。第一个是您传递给 lerp 的开始/结束值:

Vector3.Lerp(transform.localScale * 0.1f, transform.localScale, 5f * Time.deltaTime);

在您的第二帧上,.localScale大致是(0.1, 0.1, 0.1). 第二帧上 lerp的最大值是第一帧的值。这意味着您当前的代码正在无休止地缩小目标 - 与您想要的相反。

另一个问题是你处理时间的方式。你正在通过5f * Time.deltaTime,它(可能)总是小于 1。这意味着你永远不会达到最大值。

因此,要解决这些问题,您需要做两件事:首先,您需要确保您的最小/最大值实际上是最小/最大值,而不是介于两者之间的任意值。其次,您需要确保您的第三个参数在定义的时间内从 0 平稳地进展到 1。

像这样的东西:

public float ScaleTime = 5f; // the time it'll take to grow, settable in the inspector

public float ScaleTime = 5f; // the time it'll take to grow, settable in the inspector

Vector3 _targetScale;
Vector3 _startScale;
float _currentLerp = 0f;

void Start()
{
    _targetScale = this.localScale;
    _startScale = _targetScale * 0.1f;
}

void Update()
{
    _currentLerp += Time.deltaTime * ScaleTime;

    if (_currentLerp < 1)
    {
        transform.localScale = Vector3.Lerp(_startScale, _targetScale, _currentLerp);
    }
    else
    {
        transform.localScale = _targetScale; // make sure we definitely hit the target size

        ... do whatever else you need to do here...
    }
}
于 2016-09-30T14:14:00.650 回答
1

根据https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html您的第三个参数

transform.localScale = Vector3.Lerp(transform.localScale * 0.1f, transform.localScale, 5f * Time.deltaTime);

应该指示“fracJourney”,换句话说,它应该从 0f 变为 1f 以指示动画的进度,但 Time.deltaTime 会给你自上一帧以来的时间,这样你可能会看到它在 0.005 左右跳跃(或无论您的帧速率是多少)。

您需要添加另一个变量来指示动画的进度:

public float speed = 1.0F;
private float startTime;

void Start() {
    startTime = Time.time;
    normalScale = transform.localScale;
}

void Update()
{
    float distCovered = (Time.time - startTime) * speed;

    transform.localScale = Vector3.Lerp(Vector3.zero, normalScale, distCovered);
    // destroy item
    if (transform.localScale >= normalScale)
    {
        startTime = Time.time; // Reset the animation
    }
}
于 2016-09-30T14:06:31.443 回答