光线追踪框交集 (c++)

Ray tracing box intersection (c++)

本文关键字:c++ 光线追踪      更新时间:2023-10-16

我有 2 个实体和它们之间的一堵墙,我试图使用光线追踪交叉点检测碰撞,但由于某种原因它没有检测到边界框。我正在使用现有的ray,vector3和box类。

射线类:

class Ray {
  public:
    Ray() { }
    Ray(Vector3 o, Vector3 d) {
      origin = o;
      direction = d;
      inv_direction = Vector3(1/d.x(), 1/d.y(), 1/d.z());
      sign[0] = (inv_direction.x() < 0);
      sign[1] = (inv_direction.y() < 0);
      sign[2] = (inv_direction.z() < 0);
    }
    Ray(const Ray &r) {
      origin = r.origin;
      direction = r.direction;
      inv_direction = r.inv_direction;
      sign[0] = r.sign[0]; sign[1] = r.sign[1]; sign[2] = r.sign[2];
    }
    Vector3 origin;
    Vector3 direction;
    Vector3 inv_direction;
    int sign[3];
};

盒子类:

bool Box::intersect(const Ray &r, float t0, float t1) const {
  float tmin, tmax, tymin, tymax, tzmin, tzmax;
  tmin = (parameters[r.sign[0]].x() - r.origin.x()) * r.inv_direction.x();
  tmax = (parameters[1-r.sign[0]].x() - r.origin.x()) * r.inv_direction.x();
  tymin = (parameters[r.sign[1]].y() - r.origin.y()) * r.inv_direction.y();
  tymax = (parameters[1-r.sign[1]].y() - r.origin.y()) * r.inv_direction.y();
  if ( (tmin > tymax) || (tymin > tmax) ) 
    return false;
  if (tymin > tmin)
    tmin = tymin;
  if (tymax < tmax)
    tmax = tymax;
  tzmin = (parameters[r.sign[2]].z() - r.origin.z()) * r.inv_direction.z();
  tzmax = (parameters[1-r.sign[2]].z() - r.origin.z()) * r.inv_direction.z();
  if ( (tmin > tzmax) || (tzmin > tmax) ) 
    return false;
  if (tzmin > tmin)
    tmin = tzmin;
  if (tzmax < tmax)
    tmax = tzmax;
  return ( (tmin < t1) && (tmax > t0) );
}

这是我检查光线是否穿过盒子的方法:

bool Area::CheckForWalls(Vector3 point1, Vector3 point2) {
    //point1 is entity #1 @ Vector(246.98, 0.45, -487.84)
    //point2 is entity #2 @ Vector(236.60, 0.32, -483.84)
    Vector3 direction = point1.crossVector3D(point2);
    Ray* ray = new Ray(point1, direction);
    float distance = sqrt((point1.x() - point2.x()) * (point1.x() - point2.x()) +
        (point1.y() - point2.y()) * (point1.y() - point2.y()) +
        (point1.z() - point2.z()) * (point1.z() - point2.z()));
    // box corner 1: (243.03, 1.00, -480.04) and corner 2: (240.02, -2.00, -491.46)
    if (bounding_box->intersect(*ray, -2, distance)) {
        return true;
    }

    return false;
}

我想知道问题是否与光线的距离或方向有关,任何帮助将不胜感激。

我认为

您的AABB-Ray测试无效。你应该看看"一个高效而强大的射线盒交集算法"