簡體   English   中英

C++:你如何根據地形高度更新玩家高度?

[英]C++: how do you update player height based on height of terrain?

我曾經有一個項目,它使用灰度圖像在一個簡單的平面網格中設置頂點的高度,從而得到漂亮的高度映射地形。 但是,我已經將我的項目轉換為 C++,並且不能再使用 BufferedImage 等的幫助來使用舊的灰度方法從平面網格創建高度映射的地形。

因此,我的 C++ 項目現在使用 .obj 文件作為地形,但我發現當用戶在地形中走動時更新播放器/相機高度非常困難,相反我只是漂浮在所有東西中,因為播放器高度永遠不會改變或者只是經常這樣做(所以我知道高度至少正在更新,只是不正確)。

Bellow 是一個小代碼示例,它根據terrain.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());
        }

    }

你現在正在做的事情效率很低; 如果您已經有了可用於更新玩家位置的高度圖,則不必遍歷所有頂點。

為什么不將高度圖存儲在偽二維數組中,如下所示:

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 超出范圍等錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM