【问题标题】:C++: how do you update player height based on height of terrain?C++:如何根据地形高度更新玩家高度?
【发布时间】:2020-02-02 23:36:42
【问题描述】:

我曾经有一个项目,它使用灰度图像来设置简单平面网格中顶点的高度,从而生成漂亮的高度映射地形。但是,我已经将我的项目转换为 C++ 并且不能再使用 BufferedImage 等的帮助来使用旧的灰度方法从平面网格创建高度映射的地形。

因此,我的 C++ 项目现在使用 .obj 文件作为地形,但我发现当用户在地形上行走时更新播放器/相机高度非常困难,而我只是作为播放器漂浮在所有物体上高度从不改变,或者只是非常频繁地改变(所以我知道高度至少在更新,只是不正确)。

Bellow 是一个基于地形.obj 文件实际更新玩家高度的代码示例,它通过存储 .obj 文件的所有顶点并将它们的每个 x 和 z 分量与玩家的 x 和 z 分量,如果有匹配则将玩家的 y 值设置为当前顶点 y 位置:

Vector3f *playerPos = freeMoveObjects[0]->GetParent()->GetTransform()->GetPos();
    float playerXPos = playerPos->GetX();
    float playerZPos = playerPos->GetZ();
    int playerXPosInt = (int)playerXPos;
    int playerZPosInt = (int)playerZPos;
    for (Vector3f currentVector : meshObjects[0]->getMeshVertices()) {
        int meshHeightXInt = (int)currentVector.GetX();
        int meshHeightZInt = (int)currentVector.GetZ();
        if (meshHeightXInt == playerXPosInt & meshHeightZInt == playerZPosInt){//currentVector.GetX() <= playerXPos & currentVector.GetZ() <= playerZPos) {
            freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->SetY(currentVector.GetY());
        }

    }

【问题讨论】:

  • 网格和玩家位置是否可能使用不同的比例?即,一个方格的网格覆盖不止一个方格的玩家位置?

标签: c++ heightmap


【解决方案1】:

你现在的工作效率很低;如果您已经有一个可用于更新玩家位置的高度图,则不必遍历所有顶点。

为什么不将高度图存储在伪二维数组中,如下所示:

class HeightMap {
private:
int width;
int height;
std::unique_ptr<int[]> data = std::make_unique<int[]>(width * height);

public:
HeightMap(int width, int height) : width{width}, height{height} {}
// you can default copy, move constructors and assignments

int heightAt(int x, int y) {
    return heightmap[x + y * width];
}
}

使用heightAt,您现在可以高效地随机访问地图中的数据。感谢unique_ptr,您无需手动管理任何内存,并且可以默认其他构造函数。

请注意,您需要手动处理 x 或 y 超出范围等错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 2014-11-29
    • 2019-10-21
    • 2012-04-22
    • 1970-01-01
    • 2015-05-06
    • 2022-06-23
    相关资源
    最近更新 更多