I need the intersection between a ray and a rectangle. So far I have followed the answer here, but after testing it (as explained below) I realized that the implementation is wrong.
bool checkRayLightIntersection(Vec Origin, Vec Dir) {
//(-10,20,9) is Hard-code of the light position and we add (5.0f) on X and Z axis to
//make it an area instead of a vertex
//"Origin" is the position of the eye. Hard coded: (-25, 8, 5)
//"Dir" is LightPosition - Origin
float randX = 5.0f; //in the future it will be random, that's why this name
float randZ = 5.0f;
Vec P1 = Vec(-10 - randX, 20, 9 + randZ);
Vec P2 = Vec(-10 + randX, 20, 9 + randZ);
Vec P3 = Vec(-10 + randX, 20, 9 - randZ);
Vec P4 = Vec(-10 - randX, 20, 9 - randZ);
//the majority of the methods first find out where the ray intersects the
//plane that the rectangle lies on, Ax + By + Cz + D = 0
//in our case the equation of that plane is easy (I think) -> D = 20
float t = -(-Origin.y + 20) / (-Dir.y);
if (t > 0) {
Vec hitPoint = Origin + Dir * t;
Vec V1 = (P2 - P1).norm();
Vec V3 = (P4 - P3).norm();
Vec V4 = (hitPoint - P1).norm();
Vec V5 = (hitPoint - P3).norm();
float V1dotV4 = V1.dot(V4);
float V3dotV5 = V3.dot(V5);
if (V1dotV4 > 0 && V3dotV5 > 0) {
return true;
}
}
return false;
}
My Vec is a struct defined as follows:
struct Vec {
double x, y, z; // position, also color (r,g,b)
Vec(double x_ = 0, double y_ = 0, double z_ = 0){ x = x_; y = y_; z = z_; }
Vec operator+(const Vec &b) const { return Vec(x + b.x, y + b.y, z + b.z); }
Vec operator-(const Vec &b) const { return Vec(x - b.x, y - b.y, z - b.z); }
Vec operator-() const { return Vec(-x, -y, -z); }
Vec operator*(double b) const { return Vec(x*b, y*b, z*b); }
Vec operator/(double b) const { return Vec(x / b, y / b, z / b); }
Vec mult(const Vec &b) const { return Vec(x*b.x, y*b.y, z*b.z); }
Vec& norm(){ return *this = *this * (1 / sqrtf(x*x + y*y + z*z)); }
double dot(const Vec &b) const { return x*b.x + y*b.y + z*b.z; }
// cross:
Vec operator%(Vec&b){ return Vec(y*b.z - z*b.y, z*b.x - x*b.z, x*b.y - y*b.x); }
double max() const { return x>y && x>z ? x : y > z ? y : z; }
};
I tested the method. So what I tried to do is creating a ray from my Origin to a point that should be outside the Rectangle such as (-10, 20, 19), I added 9 to the Z-axis while the rectangle should be only 5 units larger in each direction (X,-X,Z,-Z). Therefore in my case:
Dir = (-10, 20, 19) - Orig
The method returns true when instead it should return false. Can you please help me understand what I am doing wrong? Thanks in advance.