線と矩形の交点が必要です。これまでのところ私は答えhereに従っていますが、テストした後(以下で説明します)、実装が間違っていることに気付きました。C++での線と矩形の交点
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;
}
私Vecとは、次のように定義された構造体である:
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; }
};
私は方法をテストしました。だから私がやろうとしたことは、Originから(-10,20,19)のようなRectangleの外にあるはずの点に線を作成することです。私はZ軸に9を加えましたが、長方形は5単位だけ大きくする必要がありました各方向(X、-X、Z、-Z)に移動します。したがって、私の場合:
Dir = (-10, 20, 19) - Orig
代わりにfalseを返す必要がある場合、このメソッドはtrueを返します。 私が間違っていることを理解してもらえますか?前もって感謝します。
によって長方形のちょうど2つの垂直エッジに対して
hitPoint
をチェックすることでこれを行うことができます。三角形と光線の交点を計算することは、コンピュータグラフィックスでは非常に一般的な問題です。[link](https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm)を参照してください。あなたの四角形は2つの三角形で構成されています – Jonas2つの三角形を使用した場合、対角線に沿って失敗する可能性があります。ポイントは、いずれの三角形の内側にもないことがあります。すべての点で重複を保証するように注意する必要があります。 – stark