c++写一个判断三维空间中判断射线与平面是否相交
时间: 2023-10-03 16:05:28 浏览: 64
下面是一个简单的 C++ 代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
struct Vector3
{
double x, y, z;
Vector3() {}
Vector3(double x, double y, double z) : x(x), y(y), z(z) {}
Vector3 operator+(const Vector3& other) const
{
return Vector3(x + other.x, y + other.y, z + other.z);
}
Vector3 operator-(const Vector3& other) const
{
return Vector3(x - other.x, y - other.y, z - other.z);
}
Vector3 operator*(double scalar) const
{
return Vector3(x * scalar, y * scalar, z * scalar);
}
double dot(const Vector3& other) const
{
return x * other.x + y * other.y + z * other.z;
}
Vector3 cross(const Vector3& other) const
{
return Vector3(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x);
}
double length() const
{
return sqrt(x * x + y * y + z * z);
}
};
struct Ray
{
Vector3 origin, direction;
Ray() {}
Ray(const Vector3& origin, const Vector3& direction) : origin(origin), direction(direction) {}
};
struct Plane
{
Vector3 point, normal;
Plane() {}
Plane(const Vector3& point, const Vector3& normal) : point(point), normal(normal) {}
};
bool intersect(const Ray& ray, const Plane& plane, double& t)
{
double denom = plane.normal.dot(ray.direction);
if (abs(denom) < 1e-6) // 判断是否平行
return false;
t = plane.normal.dot(plane.point - ray.origin) / denom;
return t >= 0;
}
int main()
{
// 示例:射线由点(0, 0, 0)出发,方向为(1, 1, 1);平面上的一点为(0, 0, 1),法向量为(0, 0, 1)
Ray ray(Vector3(0, 0, 0), Vector3(1, 1, 1));
Plane plane(Vector3(0, 0, 1), Vector3(0, 0, 1));
double t;
if (intersect(ray, plane, t))
{
Vector3 intersection = ray.origin + ray.direction * t;
cout << "Intersection point: (" << intersection.x << ", " << intersection.y << ", " << intersection.z << ")" << endl;
}
else
{
cout << "No intersection." << endl;
}
return 0;
}
```
这里我们定义了三个结构体:`Vector3` 表示三维向量,`Ray` 表示射线,`Plane` 表示平面。`intersect` 函数判断射线与平面是否相交,并返回相交参数t。在主函数中,我们给出了一个示例并输出相交点的坐标。