射线与平面相交检测程序

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值