光线跟踪盒交叉点(c ++)

时间:2014-11-13 02:45:38

标签: c++

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

光线类:

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];
};

Box class:

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;
}

我想知道问题是关于光线的距离还是方向,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

我认为您的AABB-Ray测试无效。你应该看一下“An Efficient and Robust Ray-Box Intersection Algorithm