http://www.azure.com.cn/default.asp?cat=14&page=4参照此blog,写了个射线与平面的相交检测程序:
Ray类和Plane类:
#pragma once
#include <d3dx9.h>
#include "Plane.h"
class Ray
{
public:
Ray(void);
Ray(D3DXVECTOR3 RayOrig,D3DXVECTOR3 RayDir);
~Ray(void);
bool GetHitStatus(Plane& plane);
float GetHitDistance(Plane& plane);
private:
D3DXVECTOR3 RayOrigin;
D3DXVECTOR3 RayDirec;
float dist; // ray的起点与交点的距离
bool IsHit;
};
#include "Ray.h"
#include <iostream>
using namespace std;
Ray::Ray(void)
{
RayOrigin.x = 0.0f;
RayOrigin.y = 0.0f;
RayOrigin.z = 0.0f;
RayDirec.x = 1.0f;
RayDirec.y = 1.0f;
RayDirec.z = 1.0f;
dist = 0.0f;
}
Ray::Ray(D3DXVECTOR3 RayOrig,D3DXVECTOR3 RayDir)
{
RayOrigin = RayOrig;
RayDirec = RayDir;
dist = 0.0f;
}
Ray::~Ray(void)
{
}
bool Ray::GetHitStatus( Plane& plane)
{
// if true , the ray is hitted or false the ray is not hitted
D3DXVECTOR3 vNorPlane;
vNorPlane.x = plane.a;
vNorPlane.y = plane.b;
vNorPlane.z = plane.c;
float res = 0.0f;
res =D3DXVec3Dot(&vNorPlane,&RayDirec);
if(res <= 0.0f)
{
cout<<"It is hitted"<<endl;
return true;
}
else
{
cout<<"It can not be hitted"<<endl;
return false;
}
}
float Ray::GetHitDistance(Plane& plane)
{
float nom = 0.0f;
float dist = 0.0f;
float denom = 0.0f;
// float nom = dotproduct(p.normal(), r.start()) + p.d();
D3DXVECTOR3 vNormPlane;
vNormPlane=plane.GetNormPlane();
nom = D3DXVec3Dot(&vNormPlane,&RayOrigin)+plane.d;
// float denom = dotproduct(p.normal(), r.direction());
denom = D3DXVec3Dot(&vNormPlane,&RayDirec);
dist = -(nom/denom);
return dist;
}
//////////////////////////////
#pragma once
#include <d3dx9.h>
class Plane:public D3DXPLANE
{
public:
Plane(void);
Plane(float a, float b, float c,float d);
~Plane(void);
D3DXVECTOR3 GetNormPlane();
private:
D3DXVECTOR3 vNormPlane; // 必须是单位
};
#include "Plane.h"
#include <math.h>
#include <iostream>
using namespace std;
Plane::Plane(void)
{
}
Plane::Plane(float a, float b, float c,float d):D3DXPLANE(a,b,c,d)
{
}
Plane::~Plane(void)
{
}
// Get the normal of the plane
D3DXVECTOR3 Plane::GetNormPlane()
{
float length = sqrt(a*a+b*b+c*c);
D3DXVECTOR3 v(a/length,b/length,c/length);
cout<<v.x<<" "<<v.y<<" "<<v.z<<endl;
return v;
}
#include "Ray.h"
#include "Plane.h"
#include <d3dx9.h>
#include <iostream>
using namespace std;
int main()
{
Plane plane(-1.0f,-1.0f,-1.0f,1.0f);
D3DXVECTOR3 vOri(0.0f,0.0f,0.0f);
D3DXVECTOR3 vDir(0.0f,1.0f,0.0f);
Ray *ray = new Ray(vOri,vDir);
ray->GetHitStatus(plane);
float dist = ray->GetHitDistance(plane);
cout<<"ray起点与其交点的距离为:"<<dist<<endl;
cin.get();
}