地形碰撞问题

Terrain Collision issues

我正在尝试为我的高度图地形实施地形碰撞,我正在关注 this。本教程是针对 java 的,但我使用的是 C++,尽管原理相同,所以应该没有问题。

首先,我们需要一个函数来根据相机的位置获取地形的高度。 WorldX 和 WorldZ 是相机的位置 (x, z),高度是包含所有顶点高度的二维数组。

float HeightMap::getHeightOfTerrain(float worldX, float worldZ, float heights[][256])
{   
    //Image is (256 x 256)
    float gridLength = 256;
    float terrainLength = 256;

    float terrainX = worldX;
    float terrainZ = worldZ;
    float gridSquareLength = terrainLength / ((float)gridLength - 1);
    int gridX = (int)std::floor(terrainX / gridSquareLength);
    int gridZ = (int)std::floor(terrainZ / gridSquareLength);

    //Check if position is on the terrain
    if (gridX >= gridLength - 1 || gridZ >= gridLength - 1 || gridX < 0 || gridZ < 0)
    {
        return 0;
    }

    //Find out where the player is on the grid square
    float xCoord = std::fmod(terrainX, gridSquareLength) / gridSquareLength;
    float zCoord = std::fmod(terrainZ, gridSquareLength) / gridSquareLength;
    float answer = 0.0;

    //Top triangle of a square else the bottom
    if (xCoord <= (1 - zCoord))
    {
        answer = barryCentric(glm::vec3(0, heights[gridX][gridZ], 0),
        glm::vec3(1, heights[gridX + 1][gridZ], 0), glm::vec3(0, heights[gridX][gridZ + 1], 1),
        glm::vec2(xCoord, zCoord));
    }

    else 
    {
        answer = barryCentric(glm::vec3(1, heights[gridX + 1][gridZ], 0),
        glm::vec3(1, heights[gridX + 1][gridZ + 1], 1), glm::vec3(0, heights[gridX][gridZ + 1], 1),
        glm::vec2(xCoord, zCoord));
    }

    return answer;
} 

为了找到相机当前所在的三角形的高度,我们使用重心插值函数。

float HeightMap::barryCentric(glm::vec3 p1, glm::vec3 p2, glm::vec3 p3, glm::vec2 pos)
{
    float det = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z);
    float l1 = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.y - p3.z)) / det;
    float l2 = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.y - p3.z)) / det;
    float l3 = 1.0f - l1 - l2;
    return l1 * p1.y + l2 * p2.y + l3 * p3.y;
}

然后我们只需要使用我们计算的高度来检查 比赛中发生碰撞

float terrainHeight = heightMap.getHeightOfTerrain(camera.Position.x, camera.Position.z, heights);
    if (camera.Position.y < terrainHeight)
    {
        camera.Position.y = terrainHeight;
    };

现在根据教程,这应该可以很好地工作,但是高度有点偏差,在某些地方甚至无法工作。我想这可能与地形的平移和缩放部分有关

    glm::mat4 model;
    model = glm::translate(model, glm::vec3(0.0f, -0.3f, -15.0f));
    model = glm::scale(model, glm::vec3(0.1f, 0.1f, 0.1f));

并且我应该将高度数组的值乘以 0.1,因为缩放会在 GPU 侧对地形进行缩放,但这并没有起到作用。

备注

在教程中,getHeightOfTerrain 函数的第一行说

float terrainX = worldX - x;
float terrainZ = worldZ - z;

其中 x 和 z 是地形的世界位置。这样做是为了获得玩家相对于地形位置的位置。我尝试使用翻译部分的值,但它也不起作用。我更改了这些行,因为它似乎没有必要。

float terrainX = worldX - x;
float terrainZ = worldZ - z;

事实上,这些线是非常必要的,除非你的地形总是在原点。

您的代码资源(教程)假设您没有以任何方式缩放或旋转地形。 xz 变量是地形的 XZ 位置,用于处理地形平移的情况。

理想情况下,您应该将世界位置向量从世界 space 转换为对象 space(使用用于地形的 model 矩阵的逆矩阵),例如

vec3 localPosition = inverse(model) * vec4(worldPosition, 1)

然后使用localPosition.xlocalPosition.z代替terrainXterrainZ