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

Mathf.Lerp值未按预期增长,Unity物体无法实现加速往复移动

问题分析与解决方案

原脚本的核心问题

  • t被声明为static:这会让所有挂载该脚本的物体共享同一个t值,场景重启后t也不会重置为0,直接导致移动逻辑混乱,属于隐藏bug。
  • 用Mathf.Lerp的方式做不到加速:你当前让t线性增长(t += 0.05f * Time.deltaTime),Mathf.Lerp(minimum, maximum, t)会让物体在两点间做匀速线性移动——因为t的变化速率固定,位置的变化量也固定,自然不会有加速效果。

修正后的实现方案

要实现「每秒提升0.05f速度」的往复加速移动,得直接基于速度-位置的逻辑编写,别再依赖Lerp插值。以下是修正后的脚本:

using UnityEngine;

public class AcceleratingReciprocate : MonoBehaviour
{
    public float minX = -1000.0f;
    public float maxX = 1000.0f;
    public float acceleration = 0.05f; // 每秒提升的速度值
    private float currentSpeed = 0f;
    private int moveDirection = 1; // 1向右,-1向左

    void Update()
    {
        // 每秒按设定值提升对应方向的速度
        currentSpeed += acceleration * Time.deltaTime * moveDirection;

        // 根据当前速度更新物体位置
        transform.localPosition += new Vector3(currentSpeed * Time.deltaTime, 0, 0);

        // 检测边界并反转移动方向
        CheckBoundary();
    }

    void CheckBoundary()
    {
        float currentX = transform.localPosition.x;
        // 碰到右边界,切换向左移动
        if (currentX >= maxX)
        {
            moveDirection = -1;
            // 把位置拉回边界,避免超出范围
            transform.localPosition = new Vector3(maxX, 0, 0);
        }
        // 碰到左边界,切换向右移动
        else if (currentX <= minX)
        {
            moveDirection = 1;
            transform.localPosition = new Vector3(minX, 0, 0);
        }
    }
}

关键改动说明

  • 删掉了static的t,改用currentSpeed记录当前速度,moveDirection控制移动方向,逻辑更清晰。
  • 每秒按acceleration值提升对应方向的速度,通过currentSpeed * Time.deltaTime更新位置,真正实现加速效果。
  • 边界检测时强制把物体位置拉回边界,避免因速度过快导致物体超出设定范围。

额外调整选项

如果想让物体每次到达边界后重置速度(比如从0开始反向加速),可以在反转方向的代码里加上currentSpeed = 0f;。

内容的提问来源于stack exchange,提问作者Carta Issue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:03:19