OSG 求射线与模型的交点

osg::Node *m_node = _modelNode;//设置模型节点

    osg::Vec3 start;
    osg::Vec3 end;
    osg::ref_ptr<osgUtil::IntersectionVisitor> iv = new osgUtil::IntersectionVisitor;
    osg::ref_ptr<osgUtil::LineSegmentIntersector> ls = new osgUtil::LineSegmentIntersector(start, end);
    osgUtil::LineSegmentIntersector::Intersections intersections;       //结果集


    osg::Vec3 point;
    iv->setIntersector(ls.get());
    m_node->accept(*(iv.get()));

    if (ls->containsIntersections())
    {
        intersections = ls->getIntersections();
        osgUtil::LineSegmentIntersector::Intersections::iterator iter = intersections.begin();
        for (; iter != intersections.end(); iter++)
        {
            point = iter->getWorldIntersectPoint();
            std::cout << point.x() << "  " << point.y() << "  " << point.z() << "  " << std::endl;

        }

    }

通过设置起点终点 即可求出物体与射线交点。

osg中,可以使用`osgViewer::View::computeIntersections`函数来获取鼠标与场景中的交点。具体实现如下: ``` // 获取鼠标坐标(x,y) int x,y; // 获取视口大小(viewportWidth, viewportHeight) int viewportWidth, viewportHeight; // 获取当前窗口(viewer)的渲染器(renderingContext) osg::GraphicsContext* renderingContext = viewer->getCamera()->getGraphicsContext(); // 获取当前窗口的窗口ID(windowId) unsigned int windowId = renderingContext->getState()->getContextID(); // 创建一个LineSegment,表示从鼠标所在位置发出的一条射线 osg::ref_ptr<osg::LineSegment> ray = new osg::LineSegment; ray->set(osg::Vec3(x, viewportHeight - y - 1, 0), osg::Vec3(x, viewportHeight - y - 1, 1)); // 创建一个IntersectionVisitor,用于计算与射线相交的所有节点 osgUtil::IntersectionVisitor iv; iv.setTraversalMask(~0u); iv.setLineSegment(ray.get()); // 调用computeIntersections函数 viewer->getCamera()->accept(iv); // 获取与射线相交的第一个Drawable if (iv.hits()) { osgUtil::IntersectionVisitor::HitList& hitList = iv.getHitList(node); if (!hitList.empty()) { osgUtil::Hit& hit = hitList.front(); osg::Vec3d intersectionPoint = hit.getLocalIntersectPoint(); // 将交点坐标转换为屏幕坐标 osg::Vec3d screenPos = osg::Vec3d(intersectionPoint.x() * viewportWidth / 2 + viewportWidth / 2, intersectionPoint.y() * viewportHeight / 2 + viewportHeight / 2, 0); // 输出屏幕坐标 std::cout << "Intersection point: " << screenPos.x() << ", " << screenPos.y() << std::endl; } } ``` 其中,`node`表示场景中的根节点。此外,还需要注意调用`computeIntersections`函数前需要先调用`viewer->frame()`函数来更新场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值