1.创建射线场景查询对象,记得最后销毁
mRaySceneQuery = mSceneMgr->createRayQuery(Ray());
销毁的代码是 mSceneMgr->destroyQuery(mRaySceneQuery);
2.设置要查询的射线,下面代码是以摄像机竖直向下的射线对场景进行查询
{
Vector3 camPos = mCamera->getPosition();
Ray cameraRay(Vector3(camPos.x, 5000.0f, camPos.z), Vector3::NEGATIVE_UNIT_Y);
mRaySceneQuery->setRay(cameraRay);
3.执行场景查询
RaySceneQueryResult &result = mRaySceneQuery->execute();
这样,result中就保存了查询的结果。
RaySceneQueryResult 定义如下:
typedef std::vector<RaySceneQueryResultEntry> RaySceneQueryResult;
这是一个查询结构的列表,列表的每个条目定义如下:
struct _OgreExport RaySceneQueryResultEntry
/// Distance along the ray
Real distance;
/// The movable, or NULL if this is not a movable result
MovableObject* movable;
/// The world fragment, or NULL if this is not a fragment result
SceneQuery::WorldFragment* worldFragment;
/// Comparison operator for sorting
bool operator < (const RaySceneQueryResultEntry& rhs) const
{
return this->distance < rhs.distance;
}
};
射线可能和场景相交,也可能可其他可移动的对象(MovableObject)相交,但一次只可能和其中一个,所以 movable和
worldFragment总有一个为NULL,distance保存了交点到射线起点的距离,其中还提供了射线距离比较的运算符,这样就很容易
根据离射线起点的距离对相交的MovableObject或WorldFragment进行排序。
如果和场景相交,则得到WorldFragment保存相交的结果。
WorldFragment定义如下:
struct WorldFragment {
/// The type of this world fragment
WorldFragmentType fragmentType;
/// Single intersection point, only applicable for WFT_SINGLE_INTERSECTION
Vector3 singleIntersection;
/// Planes bounding a convex region, only applicable for WFT_PLANE_BOUNDED_REGION
std::list<Plane>* planes;
/// Custom geometry block, only applicable for WFT_CUSTOM_GEOMETRY
void* geometry;
/// General render operation structure, fallback if nothing else is available
RenderOperation* renderOp;
};
其中第一个成员就是WorldFragment的类型,这是个枚举类型,定义如下:
enum WorldFragmentType
{
/// Return no world geometry hits at all
WFT_NONE,
/// Return pointers to convex plane-bounded regions
WFT_PLANE_BOUNDED_REGION,
/// Return a single intersection point (typically RaySceneQuery only)
WFT_SINGLE_INTERSECTION,
/// Custom geometry as defined by the SceneManager
WFT_CUSTOM_GEOMETRY,
/// General RenderOperation structure
WFT_RENDER_OPERATION
};
对于射线场景查询,只要用到第三个类型的枚举值,因为射线和场景的交点是个坐标值,保存在
WorldFragment结构体中的singleIntersection成员中。
其中第二个枚举值
WFT_PLANE_BOUNDED_REGION应该指是平面同场景的碰撞结果,而WFT_CUSTOM_GEOMETRY应该是自定义几何体同场景的碰撞结果。