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

Unity视差背景脚本故障:背景无法随角色移动求助

视差背景不动问题的排查与修复

核心问题分析

原脚本存在两个致命逻辑冲突:

  1. 父物体移动与纹理偏移抵消:LateUpdate中修改transform.position让父物体跟随相机X轴移动,同时又对纹理做偏移,导致背景相对于相机的视觉位置完全不变,看起来毫无移动。
  2. 累计偏移计算逻辑缺陷:用相机初始位置到当前的总距离作为偏移量,当相机持续移动时易出现偏移异常;且未记录相机上一帧位置,无法准确计算每帧移动增量。

另外,LateUpdate本身不存在问题,改成Update后出现的自主移动,是因为相机跟随玩家的逻辑可能在FixedUpdate或其他帧阶段执行,Update中拿到的相机位置未完成更新,导致偏移计算错误。

修复步骤与完整代码

1. 移除父物体跟随代码

删除LateUpdate中transform.position = new Vector3(cam.position.x, transform.position.y, 0);这一行,避免和纹理偏移逻辑冲突。

2. 改用每帧增量计算偏移

新增lastCamPos记录相机上一帧位置,计算每帧移动增量并累加,保证偏移逻辑稳定。

3. 优化视差速度计算

用Mathf.Clamp01限制速度范围在0~1之间,避免背景在相机前方时出现速度异常。

完整修正代码

public class ParallaxController : MonoBehaviour
{
    Transform cam; // 主相机
    Vector2 distance; 
    Vector3 lastCamPos; // 上一帧相机位置

    GameObject[] backgrounds;
    Material[] mat;
    float[] backSpeed;

    float farthestBack;

    [Range(0f, 0.05f)]
    public float parallaxSpeed;

    void Start()
    {
        cam = Camera.main.transform;
        lastCamPos = cam.position;

        int backCount = transform.childCount;
        mat = new Material[backCount];
        backSpeed = new float[backCount];
        backgrounds = new GameObject[backCount];

        for (int i = 0; i < backCount; i++)
        {
            backgrounds[i] = transform.GetChild(i).gameObject;
            mat[i] = backgrounds[i].GetComponent<Renderer>().material;
        }
        BackSpeedCalculate(backCount);
    }

    void BackSpeedCalculate(int backCount)
    {
        // 找到最远的背景(相对于相机的Z轴差值最大)
        for (int i = 0; i < backCount; i++) 
        {
            float zDiff = backgrounds[i].transform.position.z - cam.position.z;
            if (zDiff > farthestBack)
            {
                farthestBack = zDiff;
            }
        }

        // 计算每个背景的视差速度,限制在0~1区间
        for (int i = 0; i < backCount; i++) 
        {
            float zDiff = backgrounds[i].transform.position.z - cam.position.z;
            backSpeed[i] = Mathf.Clamp01(1 - zDiff / farthestBack);
        }
    }

    void LateUpdate()
    {
        // 计算相机每帧的移动增量
        Vector3 delta = cam.position - lastCamPos;
        distance += new Vector2(delta.x, delta.y);

        for (int i = 0; i < backgrounds.Length; i++)
        {
            float speedX = backSpeed[i] * parallaxSpeed;
            float speedY = speedX / 2; // 不需要Y轴移动可设为0
            mat[i].SetTextureOffset("_MainTex", new Vector2(distance.x * speedX, distance.y * speedY));
        }

        // 更新上一帧相机位置
        lastCamPos = cam.position;
    }
}

验证说明

  1. 确保相机正确跟随玩家移动(比如在相机脚本的Update或FixedUpdate中更新位置)。
  2. 运行后背景会根据自身距离相机的远近,呈现不同速度的视差滚动效果,距离越远的背景移动越慢,符合预期。

内容的提问来源于stack exchange,提问作者0-0

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:11:00