今天遇到一个奇怪的现象,在控制台中写好的拾取代码,结果发现集成到qt中总是报错:
我就纳闷了。。找了一圈,网上都没找到这个错误的原因。没办法,后面没有使用addEventHandler这个方法了。
自己利用osgUtil写了一个拾取对象的函数。
代码主要参考:
使用osgUtil::PolytopeIntersector来拾取对象:
void pickModel(int x, int y, osgViewer::Viewer *m_viewer)
{
const osg::GraphicsContext::Traits* trait = m_viewer->getCamera()->getGraphicsContext()->getTraits();
y = trait->height - y;
double w(5.0f), h(5.0f);
osg::ref_ptr<osgUtil::PolytopeIntersector> picker = new osgUtil::PolytopeIntersector(osgUtil::Intersector::WINDOW, x-w, y-h, x+w, y+h);
osgUtil::IntersectionVisitor iv(picker);
m_viewer->getCamera()->accept(iv);
if(picker->containsIntersections())
{
typedef osgUtil::PolytopeIntersector::Intersections Inters;
for(Inters::iterator it = picker->getIntersections().begin();
it != picker->getIntersections().end(); it++)
{
osg::NodePath nodepath = it->nodePath;
//遍历所有与之相交的对象
}
}
}
使用osgUtil::LineSegmentIntersector类来创建与对象的交点
void PickPoint(int x, int y, osg::vec3& pnt)
{
const osg::GraphicsContext::Traits* trait = m_viewer->getCamera()->getGraphicsContext()->getTraits();
y = trait->height - y;
float nx = (x - (trait->width/2.0))/(trait->width/2.0);
float nx = (x - (trait->width/2.0))/(trait->width/2.0);
osgUtil::LineSegmentIntersector* picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersection::PROJECTION, nx, ny);
osgUtil::IntersectionVisitor iv(picker);
m_viewer->getCamera()->accept(iv);
if(picker->containsIntersections())
{
typedef osgUtil::LineSegmentIntersector::Intersections Inters;
for(Inters::iterator it = picker->getIntersections().begin();\
it != picker->getIntersections().end(); it++)
{
osg::NodePath nodepath = it->nodePath;
unsigned int idx = nodePath.size();
//查找交集节点路径中的最后一个节点
pnt = it->locakIntersectionPoint;
normal = it->localIntersectionNormal;
}
}
}
其实这两种都能得到对象。。具体有部分参数还没理解,以后再看看吧,第一个我用过,中间一些问题已经解决,下面这个可以参考着改一下。
因篇幅问题不能全部显示,请点此查看更多更全内容