You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 3D玩家对象逐步缩放至指定大小的异常问题求助

问题分析与解决方案

你的缩放效果生硬,核心原因是用了线性插值(Vector3.Lerp),它是匀速变化的,没有自然的缓入缓出效果。另外代码还有几个小问题需要修正:

  • maxScale只设置了x、y轴,z轴会保持初始值,可能导致缩放不一致
  • timer是全局变量,若后续重新触发缩放会出现异常
  • do-while循环后的大括号属于语法冗余,可移除

优化方案1:用平滑插值函数实现缓动效果

用Mathf.SmoothStep替代线性比例,它会让缩放先慢后快再慢,过渡更自然。同时修正上述代码问题:

using System.Collections;
using UnityEngine;

public class PlayerGrowth : MonoBehaviour
{
    public float growTime = 6f;
    public float maxSize = 2f;
    public bool isMaxSize = false;

    void Start()
    {
        if (!isMaxSize)
        {
            StartCoroutine(Grow());
        }
    }

    private IEnumerator Grow()
    {
        Vector3 startScale = transform.localScale;
        Vector3 maxScale = new Vector3(maxSize, maxSize, maxSize); // 补全z轴,保证三维缩放一致
        float timer = 0f; // 改为局部变量,避免全局变量污染导致重复触发异常

        do 
        {
            float progress = Mathf.SmoothStep(0f, 1f, timer / growTime);
            transform.localScale = Vector3.Lerp(startScale, maxScale, progress);
            timer += Time.deltaTime;
            yield return null;
        }
        while (timer < growTime);

        // 强制设置最终缩放值,避免浮点精度误差导致未达到目标大小
        transform.localScale = maxScale;
        isMaxSize = true;
    }
}

优化方案2:自定义缓动曲线(更灵活)

如果想自定义缩放节奏(比如先快后慢、先慢后快),可以用Unity的AnimationCurve,在Inspector面板里可视化调整曲线形状:

using System.Collections;
using UnityEngine;

public class PlayerGrowth : MonoBehaviour
{
    public float growTime = 6f;
    public float maxSize = 2f;
    // 默认使用缓入缓出曲线,可在编辑器里拖拽调整
    public AnimationCurve growCurve = AnimationCurve.EaseInOut(0,0,1,1);
    public bool isMaxSize = false;

    void Start()
    {
        if (!isMaxSize)
        {
            StartCoroutine(Grow());
        }
    }

    private IEnumerator Grow()
    {
        Vector3 startScale = transform.localScale;
        Vector3 maxScale = new Vector3(maxSize, maxSize, maxSize);
        float timer = 0f;

        do 
        {
            float progress = timer / growTime;
            // 用自定义曲线计算缓动后的进度
            float easedProgress = growCurve.Evaluate(progress);
            transform.localScale = Vector3.Lerp(startScale, maxScale, easedProgress);
            timer += Time.deltaTime;
            yield return null;
        }
        while (timer < growTime);

        transform.localScale = maxScale;
        isMaxSize = true;
    }
}

内容的提问来源于stack exchange,提问作者Umer Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 22:37:27