想请教一下 directx3d游戏开发编程 书中的拾取
首先说明,这本书的封面是一个龙头;里面在拾取一章给了三个函数,分别是计算射线、变换坐标和射线与外接球体相交测试;
我觉得之所以用外接球体,可能是因为 被拾取目标(茶壶)是不规则物体,所以用球体;
而我现在想测试一个立方体,考虑 到是规制物体;应有更好的写法;
无奈 才疏智短,没法理解第三个函数,所以想请教一下,如果外接体换成立方体的话,第三个函数的写法,或思路是什么
另附上书中的三个函数及结构体:
struct sRay {
D3DXVECTOR3 _origin;
D3DXVECTOR3 _direction;
};
struct BoundingSphere {
BoundingSphere() {};
D3DXVECTOR3 _center;
float _radius;
};
d3d::sRay d3d::CalcPickingRay(IDirect3DDevice9 *lpDevice, int x, int y) {
float px = 0.0f;
float py = 0.0f;
D3DVIEWPORT9 vp;
lpDevice->GetViewport(&vp);
D3DXMATRIX proj;
lpDevice->GetTransform(D3DTS_PROJECTION, &proj);
px = (((2.0f * x) / vp.Width) - 1.0f) / proj(0, 0);
py = (((-2.0f * y) / vp.Height) + 1.0f) / proj(1, 1);
d3d::sRay ray;
ray._origin = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
ray._direction = D3DXVECTOR3(px, py, 1.0f);
return ray;
}
void d3d::TransformRay(sRay * ray, const D3DXMATRIX * T) {
D3DXVec3TransformCoord(&ray->_origin, &ray->_origin, T);
D3DXVec3TransformNormal(&ray->_direction, &ray->_direction, T);
D3DXVec3Normalize(&ray->_direction, &ray->_direction);
}
bool d3d::RaySphereIntTest(const sRay *ray, const BoundingSphere *Sphere) {
D3DXVECTOR3 v = ray->_origin - Sphere->_center;
float b = 2.0f * D3DXVec3Dot(&ray->_direction, &v);
float c = D3DXVec3Dot(&v, &v) - (Sphere->_radius * Sphere->_radius);
float discriminant = (b * b) - (4.0f * c);
if (discriminant < 0.0f)
return false;
discriminant = sqrtf(discriminant);
float s0 = (-b + discriminant) / 2.0f;
float s1 = (-b - discriminant) / 2.0f;
if (s0 >= 0.0f || s1 >= 0.0f)
return true;
return false;
}