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

Unity随机生成平台位置超出玩家可跳跃范围问题求助

问题修复方案

核心错误原因

平台生成代码中构造新坐标时,Vector3的X、Y参数顺序写反,导致生成点持续向X轴正方向偏移,是平台全部向右上漂移的直接原因。

修复后代码

平台生成代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformGenerator : MonoBehaviour
{
    public GameObject thePlatform;
    public Transform generationPoint;
    public float distanceBetween;

    private float platformWidth;

    public float distanceBetweenMin;
    public float distanceBetweenMax;
    // 新增:X轴随机偏移范围,根据玩家水平移动最大距离调整,比如设为2代表左右最多偏移2单位
    public float horizontalRandomRange = 2f;

    // Start is called before the first frame update
    void Start()
    {
        platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;
    }

    // Update is called once per frame
    void Update()
    {
        if(transform.position.y < generationPoint.position.y)
        {
            distanceBetween = Random.Range(distanceBetweenMin, distanceBetweenMax);
            // 修复坐标顺序,Y轴累加纵向间隔,X轴增加随机偏移
            float newX = Random.Range(transform.position.x - horizontalRandomRange, transform.position.x + horizontalRandomRange);
            float newY = transform.position.y + platformWidth + distanceBetween;
            transform.position = new Vector3(newX, newY, transform.position.z);

            Instantiate(thePlatform, transform.position, transform.rotation);
        }
    }
}

平台销毁代码(适配纵向跳跃逻辑)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformDestroyer : MonoBehaviour
{
    public GameObject platformDestructionPoint;

    // Start is called before the first frame update
    void Start()
    {
        platformDestructionPoint = GameObject.Find("PlatformDestructionPoint");
    }

    // Update is called once per frame
    void Update()
    {
        // 修复判断逻辑:纵向跳跃游戏判断Y坐标低于销毁点即可销毁
        if(transform.position.y < platformDestructionPoint.transform.position.y)
        {
            Destroy(gameObject);
        }
    }
}

参数调整建议

  • distanceBetweenMin和distanceBetweenMax的区间需要小于玩家最大跳跃高度,保证玩家可以跳上上下相邻的平台
  • horizontalRandomRange的值需要小于玩家水平方向最大可移动距离的一半,避免平台偏移出玩家可到达的范围

问题效果示意图

问题效果示意图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:36:02