0
\$\begingroup\$

I have the following struct that calculates Raycasting:

struct RayCast {

    // Variables
    float zpos = -1.0f; // Camera looks down the negative Z axis
    glm::vec4 rayClip;
    glm::vec4 rayEye;
    glm::vec4 rw; // Since this doesn't work: vec3 ray_wor = (inverse(view_matrix) * ray_eye).xyz;, I need to somehow convert from vec4 to vec3. So I created a temporary "rw"
    glm::vec3 rayWorld;
    float tMinX, tMaxX, tMinY, tMaxY, tMinZ, tMaxZ;

    // Get 4D homogeneous clip coordinates
    void homogeneousClipCoords() {
        rayClip = glm::vec4(xpos, ypos, zpos, 1.0f);
    }

    // Get 4D eye camera coordinates
    void eyeCameraCoords() {
        rayEye = glm::inverse(camera.projection) * rayClip;
        rayEye = glm::vec4(rayEye.x, rayEye.y, rayEye.z, 0.0f);
    }

    // Get 4D world coordinates
    void worldCoords() {
        rw = glm::inverse(camera.view) * rayEye;
        rayWorld = glm::vec3(rw.x, rw.y, rw.z);
        rayWorld = glm::normalize(rayWorld); // THIS IS OUR RAY DIRECTION! THE RAY POSITION IS THE CAMERA POSITION!!!
    }

    void AABB(float& minX, float& maxX, float& minY, float& maxY, float& minZ, float& maxZ) {
        tMinX = (minX - camera.cameraPosition.x) / rayWorld.x;
        tMaxX = (maxX - camera.cameraPosition.x) / rayWorld.x;
        tMinY = (minY - camera.cameraPosition.y) / rayWorld.y;
        tMaxY = (maxY - camera.cameraPosition.y) / rayWorld.y;
        tMinZ = (minZ - camera.cameraPosition.z) / rayWorld.z;
        tMaxZ = (maxZ - camera.cameraPosition.z) / rayWorld.z;
    }
};

In my object properties, I have a function that operates on AABB too:

void Object::AABB(float& tMinX, float& tMaxX, float& tMinY, float& tMaxY, float& tMinZ, float& tMaxZ) {
    if (tMaxX > minX && tMinX < maxX && tMaxY > minY && tMinY < maxY && tMaxZ > minZ && tMinZ < maxZ) {
        std::cout << "collision!" << std::endl;
    }
}

Now, in my render loop I have:

for (int i = 0; i < objects.size(); i++) {
    ray.AABB(objects[i]->minX, objects[i]->maxX, objects[i]->minY, objects[i]->maxY, objects[i]->minZ, objects[i]->maxZ);
    objects[i]->AABB(ray.tMinX, ray.tMaxX, ray.tMinY, ray.tMaxY, ray.tMinZ, ray.tMaxZ);
}

The Raycasting works, meaning I get a direction vector pointing from the mouse. The camera position is also accurate. What I seem to struggle with is using that Raycasting direction of the mouse to detect collision. Nothing happens when I hover over the cube in my scene.

\$\endgroup\$

0

You must log in to answer this question.

Browse other questions tagged .