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

游戏开发中嵌套forEach遍历同数组判断平台上下关系问题

平台上方判断的代码问题修复

你的这段代码没法正常工作,主要是三个核心问题:

  1. 没有排除自身对比
    嵌套遍历的时候,每个平台都会和自己进行对比,这时候条件platform.y -1 <= other_platform.y + other_platform.height必然成立,直接把所有平台的isSurface设为false,结果所有平台都被错误标记。

  2. 缺少水平重叠判断
    你只判断了Y轴方向的位置,但没考虑X轴是否重叠。哪怕两个平台在水平方向完全不挨着,只要Y轴满足条件就会被判定成有遮挡,这显然不符合游戏里的实际逻辑。

  3. 初始状态和逻辑顺序错误
    你没有先给isSurface设置初始值(应该默认是true,代表是表面平台),而是直接在循环里设为false,导致状态混乱。


修正后的代码

先给所有平台初始化表面状态,再进行两两对比:

// 先默认所有平台都是表面
platforms.forEach(platform => {
  platform.isSurface = true;
});

// 嵌套遍历对比,排除自身并增加水平重叠判断
platforms.forEach(platform => {
  platforms.forEach(otherPlatform => {
    // 跳过自己和自己的对比
    if (platform === otherPlatform) return;

    // 判断otherPlatform是否在platform的正下方且水平重叠
    const hasVerticalOverlap = platform.y <= otherPlatform.y + otherPlatform.height + 1;
    const hasHorizontalOverlap = 
      platform.x < otherPlatform.x + otherPlatform.width && 
      platform.x + platform.width > otherPlatform.x;

    // 如果下方有重叠的平台,标记当前平台不是表面
    if (hasVerticalOverlap && hasHorizontalOverlap) {
      platform.isSurface = false;
    }
  });
});

更高效的写法(用some替代内层forEach)

some方法会在找到第一个符合条件的元素后立即停止遍历,比嵌套forEach性能更好:

platforms.forEach(platform => {
  // 只要存在一个在下方且重叠的平台,当前就不是表面
  platform.isSurface = !platforms.some(otherPlatform => {
    if (platform === otherPlatform) return false;
    
    const hasVerticalOverlap = platform.y <= otherPlatform.y + otherPlatform.height + 1;
    const hasHorizontalOverlap = 
      platform.x < otherPlatform.x + otherPlatform.width && 
      platform.x + platform.width > otherPlatform.x;

    return hasVerticalOverlap && hasHorizontalOverlap;
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:55:09