【问题标题】:How can I fix my collisions for a platformer type game?如何解决平台类型游戏的碰撞问题?
【发布时间】:2021-05-28 13:25:03
【问题描述】:

我正在使用 OpenGL、EnTT 和 C++ 尝试重建超级马里奥世界。目前,当我向一个方向移动玩家并且它与固体块发生碰撞时,碰撞检测和解决效果很好。但是,当玩家在不断向墙壁移动的同时尝试跳跃时,会触发顶部碰撞,导致玩家停下并跌倒。我已经在互联网上搜索了一段时间,但我无法解决这个问题。如有任何建议或意见,我将不胜感激。

碰撞码:

void GameUI::collision(const entt::entity &entity, const entt::entity &object) {
    const auto &ent {registry.get<Hitbox>(entity)};
    auto &phys {registry.get<Physics>(entity)};
    const auto &obj {registry.get<Hitbox>(object)};

    if (ent.btm >= obj.top || ent.top <= obj.btm
        || ent.left >= obj.right || ent.right <= obj.left)
        return;

    if (ent.btm < obj.top && ent.btm - phys.yVel >= obj.top) { // Bottom Collision
        moveY(entity, obj.top - ent.btm);
        phys.yVel = 0;
    } else if (ent.top > obj.btm && ent.top - phys.yVel <= obj.btm) { // Top Collision
        moveY(entity, obj.btm - ent.top);
        phys.yVel = 0;
    } else if (ent.left < obj.right && ent.left - phys.xVel >= obj.right) { // Left Collision
        moveX(entity, obj.right - ent.left);
        phys.xVel = 0;
    } else if (ent.right > obj.left && ent.right - phys.xVel <= obj.left) { // Right Collision
        moveX(entity, obj.left - ent.right);
        phys.xVel = 0;
    }
}

【问题讨论】:

  • 首先准确定义应该发生什么。通过设置断点或将数据写入控制台或文件来确定实际发生的情况。我怀疑您遇到的是玩家在墙内移动并且具有xy 速度,并且由于您的“顶部”测试首先发生,您只需处理然后退出。如果您希望在两个轴上独立碰撞,请删除 left &lt; right 测试。也许这会让你更接近你期望发生的任何事情。

标签: c++ collision-detection collision


【解决方案1】:

您无需进行任何边界检查以查看您是否实际上在任何给定方向撞到墙上。当函数检测到您正在剪辑时(并且没有立即从顶部返回),就会发生这种情况。

      The actual wall -->  ######### ------------ <-- The plane where the wall lies
                                   # o_
                                   # /\    <-- You, hitting your head on the top plane
                                   #  |\
                                   #
                                   # | | |

因为顶部碰撞检查之前侧面碰撞。

if (ent.top > obj.btm && ent.top - phys.yVel <= obj.btm)

即使你可能没有从墙底剪下来,你是:

  • 墙内(功能不会立即返回)
  • 在其顶部下方
  • 并且有向上的速度

...其中包括检测顶部碰撞的所有条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多