如何在 raycaster 游戏引擎中检测光线击中墙壁的哪一侧?

问题描述 投票:0回答:1

我从两天前就开始写光线投射器了。我正在使用一种简单而快速的算法来使用射线检测墙壁。顺便说一句,这是C。我的问题是:我应该使用什么检查来检测射线击中了墙壁的哪一面?我一直在考虑检查射线 Y 分量是否大于射线 X 分量,这意味着我击中了左右面。正确的?我不太确定。 完整代码在这里:

    double rayAngle, wallX, wallY, rayX, rayY, h, distance, lineHeight, lineOffset, cameraAngle, shadeDistance;
    for (double ray = 0; ray < FOV * RAY_PER_DEG; ray++) // we want to raycast FOV * RAYS_PER_DEG rays
    {
        rayAngle = playerAngle + TO_RADIANS(ray / RAY_PER_DEG - FOV / 2); // set the ray angle derived from the ray index
        wallX = playerX; // set current wall coordinates to player's
        wallY = playerY; //
        rayY = sin(rayAngle) * DISTANCE_COEFFICIENT; // use vector decomposition to determine X and Y components of the ray
        rayX = cos(rayAngle) * DISTANCE_COEFFICIENT; // 
 
        for(distance = 0; distance < MAX_DISTANCE; distance++) // check for ray collision
        {
            wallX = wallX + rayX; // increase wall coordinates
            wallY = wallY + rayY;
 
            if (wallX < mapWidth && wallY < mapHeight &&       // check for wall boundaries
                wallX >= 0 && wallY >= 0 &&
                mapWalls[(int)wallY * mapHeight + (int)wallX]) // check for wall to be present
            {
                break;
            }
        }
 
        // fisheye compensation
        cameraAngle = playerAngle - rayAngle; // determine the camera angle
        WRAP_AROUND_RADIANS(cameraAngle);
        distance = distance * cos(cameraAngle); // adjust distance by x component of camera angle
 
        lineHeight = WALL_HEIGHT * MAX_WALL_HEIGHT / distance;
        lineOffset = WALL_HEIGHT - lineHeight/2; // move the line at middle
 
        // draw the ray on the map
        shadeDistance = 1 / distance;
 
        glLineWidth(1 / RESOLUTION);
        glBegin(GL_LINES);
        glColor3f(shadeDistance * SHADE_COEFFICIENT, 0, 0); // wall
        glVertex2f(ray / RESOLUTION, lineHeight + lineOffset);
        glVertex2f(ray / RESOLUTION, lineOffset);
 
        glColor3f(0, shadeDistance * SHADE_COEFFICIENT, 0); // floor
        glVertex2f(ray / RESOLUTION, lineOffset);
        glVertex2f(ray / RESOLUTION, 0);
        glEnd();
    }

https://pastebin.com/BsNYvXPf 请随意告诉我有关代码的任何信息。 编辑:我必须知道这一点才能实现纹理映射。

c math raycasting
1个回答
1
投票

用参数坐标表示射线

x = x0 + dx * t
y = y0 + dy * t

在你的情况下

dx=cos(rayAngle), dy=sin(rayAngle)
(dx,dy)
是单位方向向量。

检查垂直线和水平线的交点

 x0 + dx * t1 = wallX
 y0 + dy * t2 = wallY 

获取t1,t2

t1 = (wallX - x0) / dx
t2 = (wallY - y0) / dy

t1,t2
中的较小值告诉我们首先会遇到哪堵墙。

increase wall coordinates
- 墙壁会移动吗?

© www.soinside.com 2019 - 2024. All rights reserved.