【问题标题】:Finding Closest coordinates on Terrain OpenGL在地形 OpenGL 上查找最近的坐标
【发布时间】:2013-12-24 13:51:31
【问题描述】:

我正在使用 C++ 在 OpenGL 中制作游戏。我的地形有山丘等,我希望角色能够在山上上下行走。为此,我创建了一个函数,试图找到最近的坐标并返回相应的 y 坐标,但它不起作用,我的角色只是保持在相同的高度。这是我的功能:

float ViewPort::comparePosition(float xPos, float zPos) {
int closestValSoFar = 0;

for (int unit = 0; unit < sizeof(desert_scene_plainVerts)/sizeof(desert_scene_plainVerts[0]); unit++){
    int xDifference = terrainxPos[unit] - xPos;
    int zDifference = terrainzPos[unit] - zPos;
    int combinedDifferece = xDifference + zDifference;

    if (unit == 0) {
        closestValSoFar = unit;
    }
    if (combinedDifferece < (terrainxPos[unit-1] - xPos) + (terrainzPos[unit-1] - zPos)) {
        closestValSoFar = unit - 1;
    }
    else {
        closestValSoFar = unit;
    }
    if ((unit - 1) < sizeof(desert_scene_plainVerts)/sizeof(desert_scene_plainVerts[0])) {
        return terrainyPos[closestValSoFar];
    }

}

return terrainyPos[closestValSoFar];

}

我正在调用它并将其与此代码一起使用:

float yPos = ViewPort::comparePosition(Camera::position.x, Camera::position.z);
Camera::position.y = yPos+1.65;

有人知道如何修复我的代码吗?

【问题讨论】:

  • 你有一个非常奇怪的使用sizeof的方式...如果数组的大小是堆栈然后输入它而不是sizeof...如果大小不是静态的然后@ 987654325@ 不起作用(给出正确的“长度”)。
  • 但我认为长度是sizeof(verts)/sizeof(verts[0])
  • 如果您的 verts 数组的大小是静态的,那么应该返回该大小,但如前所述,如果您的数组不是静态的,那么它会给您带来问题。
  • 您能否详细说明“最近坐标”的含义?什么坐标?最接近什么?对你的角色?
  • 距离角色最近的地形坐标

标签: c++ opengl terrain


【解决方案1】:

如果我理解正确,您是在尝试通过比较对象的位置和给定位置的地形高度来执行地形钳制;但最常见的方法是执行从对象位置到地形的光线投射。然后检查光线是否拦截地形以及它发生的位置。

但是用openGL做游戏真的很难,你为什么不试试像OGRE这样的3d引擎呢?

【讨论】:

  • 请作为 cmets 提问。欢迎来到 SO。
  • 并非所有问题都必须是 cmets。这个问题是另一种说法“你可能想考虑这种其他方式来做”,这是一种有效的(如果不喜欢的话)答案形式。
【解决方案2】:

如果你打算这样做,因为我喜欢这种简单的方法,我会简单地重写一下函数。老实说,我认为您的方法可以再简化一点。

我做了一些修改并把它放在这里。我更改了勾股定理的加法以略微提高准确性,但如果它导致性能显着下降,我确信旧加法几乎与新方法一样有效。

float ViewPort::comparePosition(float xPos, float zPos) {
int closestValSoFar = 0;

for (int unit = 0; unit < sizeof(desert_scene_plainVerts)/sizeof(desert_scene_plainVerts[0]); unit++){
    int xDifference = terrainxPos[unit] - xPos;
    int zDifference = terrainzPos[unit] - zPos;
    int combinedDifferece = sqrt(xDifference*xDifference + zDifference*zDifference);

    if (unit == 0) {
        closestValSoFar = unit;
    }
    else if (combinedDifferece < closesValSoFar) {
        closestValSoFar = combinedDifference;
    }

}

return terrainyPos[closestValSoFar];

}

老实说,我真的很喜欢旧代码,这实际上是相同的,我只是检查了新距离是否小于最接近的ValSoFar 而不是之前的顶点。我希望这会有所帮助!

感谢您使用普通 OpenGL 制作游戏的努力,因为我也否认引擎(我不知道为什么,我只是觉得它们很无聊。我不是艺术家,我是程序员,而且引擎是艺术家和简化的东西)!我很想看看你的成品,听起来很酷!

【讨论】:

  • 为您的帮助干杯,并完全同意您对引擎的看法,宁愿自己尝试做事,没有引擎。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
相关资源
最近更新 更多