http://blog.csdn.net/fengerfafa/archive/2008/07/07/2622848.aspx
view plaincopy to clipboardprint?
//参考delta3d官方论坛上提供的方法,供交流
// 另请问 " MessageBox(NULL,lpText,NULL,MB_OK);“第一个参数HWND hWnd用this报错,怎样获取窗口句柄?
bool Picker::MBPressed (const dtCore::Mouse *mouse, dtCore::Mouse::MouseButton button)
{
if (button == dtCore::Mouse::MouseButton::MiddleButton)
{
//is there an object picked by the mouse ?
dtCore::DeltaDrawable* picked_object = NULL;
osg::Vec3 nearPoint,farPoint;
float x=0, y=0;
mouse->GetPosition(x, y);//获取鼠标坐标
osg::Matrix VPW =GetCamera()->GetOSGCamera()->getViewMatrix()* //V
GetCamera()->GetOSGCamera()->getProjectionMatrix()* //P
GetCamera()->GetOSGCamera()->getViewport()->computeWindowMatrix();//W
osg::Matrix inverseVPW;
inverseVPW.invert(VPW);
/*int xx,yy,w,h;
GetWindow()->GetPosition(xx, yy, w, h);//获取应用程序窗口大小
int xLoc = w*(x+1)/2;
int yLoc = h*(y+1)/2;*/
int xLoc = GetCamera()->GetOSGCamera()->getViewport()->width()*(x+1)/2;//width()是视口宽(注意视口不同于窗口),xLoc and yLoc are window (x,y) pixel locations
int yLoc = GetCamera()->GetOSGCamera()->getViewport()->height()*(y+1)/2;
nearPoint.set(xLoc,yLoc, 0.0f);
farPoint.set(xLoc,yLoc, 1.0f);
nearPoint=nearPoint*inverseVPW;
farPoint=farPoint*inverseVPW;
dtCore::RefPtr<dtCore::Isector> ray = new dtCore::Isector(GetScene());
osg::Vec3f xyz;
ray->Reset();
ray->SetScene(GetScene());
ray->SetStartPosition(nearPoint);
ray->SetDirection(farPoint-nearPoint);
if(ray->Update())//如果检测到射线与物体相交
{
ray->GetHitPoint(xyz);//光线与第一个物体的相交点坐标
std::cout<<"Hit Point: "<<xyz.x()<<" "<<xyz.y()<<" "<<xyz.z()<<" Num hits: "<<ray->GetNumberOfHits()<<std::endl;//???为什么点中1个输出数目是两个?如果是凹多面体那不有可能大于2次相交?
picked_object = ray->GetClosestDeltaDrawable();//光线方向最近的击中物体
std::cout<<"HIT name:"<<picked_object->GetName()<<" ID:"<<picked_object->GetUniqueId().ToString()<<std::endl;
// 将“const std::string”转换为“LPCTSTR”方法:
// std::string str;
// LPCTSTR lpstr = (LPCTSTR)str.c_str();//.c_str()是额外加的
LPCTSTR lpText = (LPCTSTR)picked_object->GetName().c_str();
MessageBox(NULL,lpText,NULL,MB_OK);//第一个参数HWND hWnd用this报错,怎样获取窗口句柄?
}
else
std::cout<<"no Point: "<<std::endl;
/* int xWin = GetCamera()->GetSceneHandler()->GetSceneView()->getViewport()->width()*(x+1)/2;
int yWin = GetCamera()->GetSceneHandler()->GetSceneView()->getViewport()->height()*(y+1)/2;
GetCamera()->GetSceneHandler()->GetSceneView()->projectWindowXYIntoObject(xWin,yWin,nearPoint,farPoint);
// create the isector
dtCore::RefPtr<dtCore::Isector> pickRay = new dtCore::Isector(GetScene());
pickRay->SetStartPosition(nearPoint);
pickRay->SetDirection(farPoint-nearPoint);
// shoot the ray
if(pickRay->Update())
{
picked_object = pickRay->GetClosestDeltaDrawable();
std::cout<<"HIT name:"<<picked_object->GetName()<<" ID:"<<picked_object->GetUniqueId().ToString()<<std::endl;
}*/
}
return false;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fengerfafa/archive/2008/07/07/2622848.aspx