上一篇文章中说了,如果使用鼠标点选隐藏模型。当时如果是同一个模型经过缩放或者平移后再次显示出来,也就是就在了一份模型但是通过平移显示出两个模型,点击其中一个模型时候回怎么样?是隐藏当前模型还是隐藏所有同类模型?
创建一个这样的场景:
void mousePick2() {
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
viewer->addEventHandler(new osgViewer::WindowSizeHandler());
viewer->addEventHandler(new MouseHandler2());
osg::ref_ptr<osg::Group> root = new osg::Group;
root->setName("ROOT");
osg::ref_ptr<osg::Node> n1 = osgDB::readNodeFile("cow.osgt");
//缩小牛模型
osg::ref_ptr<osg::MatrixTransform>mt = new osg::MatrixTransform;
mt->setName("MatrixTransform");
osg::Matrix matrix;
matrix.makeScale(osg::Vec3(0.2, 0.2, 0.2));
mt->setMatrix(matrix);
mt->addChild(n1);
//平移牛模型
osg::ref_ptr<osg::MatrixTransform>mt2 = new osg::MatrixTransform;
mt2->setName("MatrixTransform2");
osg::Matrix matrix2;
matrix2.makeTranslate(osg::Vec3(10.0, 0.0, 0.0));
mt2->setMatrix(matrix2);
mt2->addChild(n1);
osg::ref_ptr<osg::Node> n2 = osgDB::readNodeFile("xyz.osgt");
root->addChild(mt);
root->addChild(mt2);
root->addChild(n2);
viewer->setSceneData(root.get());
viewer->realize();
viewer->run();
}
首先看看鼠标点击时,输出的模型组织路径:
void MouseHandler2::pick(osgViewer::View* view, float x, float y) {
osgUtil::LineSegmentIntersector::Intersections intersections;
if (view->computeIntersections(x, y, intersections)) {
osgUtil::LineSegmentIntersector::Intersections::iterator inter = intersections.begin();//获取第一个点
const osg::NodePath& nodePath = inter->nodePath;//获取第一个交点的Path
osg::ref_ptr<osg::Node> node = new osg::Node;
for (int i = 1; i < nodePath.size() - 1; i++) {
std::string name = nodePath[i]->getName();
qDebug() << QString::fromStdString(name);
}
}
}
当点击右边大的牛模型时,输出信息:
"ROOT"
"MatrixTransform2"
"cow.osg"
当点击左边小的牛模型时:
"ROOT"
"MatrixTransform"
"cow.osg"
当点击坐标轴模型时:
"ROOT"
"axes.osg"
以上是没有问题的,完全正确;
下面修改一下代码,通过鼠标点击影藏模型:
void MouseHandler2::pick(osgViewer::View* view, float x, float y) {
osgUtil::LineSegmentIntersector::Intersections intersections;
if (view->computeIntersections(x, y, intersections)) {
osgUtil::LineSegmentIntersector::Intersections::iterator inter = intersections.begin();//获取第一个点
const osg::NodePath& nodePath = inter->nodePath;//获取第一个交点的Path
osg::ref_ptr<osg::Node> node = new osg::Node;
node = nodePath.at(nodePath.size() - 1);
if (node!=nullptr){
node->setNodeMask(0);
}
}
}
当我们通过鼠标点击右边坐标的较大的牛模型时,左边较小的牛模型也一起隐藏了。这是为什么呢?
原来它们是公用的同一份内存模型当其中一个隐藏后,另外一个显示的模型也就同事隐藏了。
解决办法:
1、读取两次同一个模型文件,在内存中保持两份,对他们的操作互不干扰;
2、通过获取它们的矩阵来隐藏它们。