osgEarth中计算绘制模型BoundingBox时方向与位置异常问题咨询
osgEarth模型包围盒方向错误解决方案
你当前实现获取的是节点局部坐标系下的轴对齐包围盒(AABB),直接乘以局部转世界矩阵后,没有适配osgEarth地理场景下的空间朝向规则,当模型挂载在带有地理坐标偏移/旋转的GeoTransform节点下时,局部坐标系的轴向和世界空间的东北天(ENU)轴向不匹配,就会出现方向错误。
修正后实现步骤
- 第一步:先获取局部包围盒的8个角点,逐个转换到世界空间,避免直接转换AABB带来的轴向错位
- 第二步:如果需要生成垂直地面且朝向和模型一致的包围盒,基于转换后的角点构建定向包围盒即可
- 第三步:绘制时直接使用世界空间下的角点坐标生成线框几何体,不需要额外做坐标转换
完整示例代码
// 1. 计算局部包围盒 osg::ComputeBoundsVisitor boundVisitor; node->accept(boundVisitor); osg::BoundingBox localBB = boundVisitor.getBoundingBox(); // 2. 获取正确的局部转世界矩阵(注意path参数要拼写正确,你原代码里的paath是拼写错误) osg::Matrixd localToWorld = osg::computeLocalToWorld(path); // 3. 遍历局部包围盒的8个角点,全部转换到世界空间 osg::Vec3d worldCorners[8]; for(int i=0; i<8; i++){ worldCorners[i] = localBB.corner(i) * localToWorld; } // 4. 基于世界空间角点生成包围盒线框 osg::ref_ptr<osg::Geometry> bbGeom = new osg::Geometry; osg::ref_ptr<osg::Vec3Array> vertexArray = new osg::Vec3Array; // 添加12条边的顶点,对应立方体线框 // 底面四条边 vertexArray->push_back(worldCorners[0]);vertexArray->push_back(worldCorners[1]); vertexArray->push_back(worldCorners[1]);vertexArray->push_back(worldCorners[2]); vertexArray->push_back(worldCorners[2]);vertexArray->push_back(worldCorners[3]); vertexArray->push_back(worldCorners[3]);vertexArray->push_back(worldCorners[0]); // 顶面四条边 vertexArray->push_back(worldCorners[4]);vertexArray->push_back(worldCorners[5]); vertexArray->push_back(worldCorners[5]);vertexArray->push_back(worldCorners[6]); vertexArray->push_back(worldCorners[6]);vertexArray->push_back(worldCorners[7]); vertexArray->push_back(worldCorners[7]);vertexArray->push_back(worldCorners[4]); // 侧面四条边 vertexArray->push_back(worldCorners[0]);vertexArray->push_back(worldCorners[4]); vertexArray->push_back(worldCorners[1]);vertexArray->push_back(worldCorners[5]); vertexArray->push_back(worldCorners[2]);vertexArray->push_back(worldCorners[6]); vertexArray->push_back(worldCorners[3]);vertexArray->push_back(worldCorners[7]); bbGeom->setVertexArray(vertexArray); bbGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertexArray->size())); // 将线框节点添加到osgEarth的根节点即可正常显示
额外注意事项
- 原代码中的
paath属于拼写错误,必须传入从目标节点到根节点的正确NodePath才能拿到正确的转换矩阵 - 如果你的模型绑定了动画或者有实时位移,需要每帧重新计算转换矩阵和角点坐标
- 如果需要获得站心坐标系下的轴对齐包围盒,可以将世界空间的8个角点转到ENU坐标系后再计算AABB,再转回世界空间绘制即可
内容的提问来源于stack exchange,提问作者peanutpig
相关产品推荐
相关产品推荐

