QScreenRayCaster找不到实体。我有什么错吗?

时间:2018-10-05 13:27:58

标签: qt3d

在Qt3D中对新QScreenRayCaster的描述似乎正是我要使用的,但是我无法让它对我有用。我想在初始化过程中我需要做一些事情,但是我找不到在线示例来指出正确的方向。我编写了一个非常简单的程序来测试该功能。它在窗口的中心绘制一个单位球体,然后在中心点触发QScreenRayCaster,据我所见,它应该返回一个命中列表,但在我的程序中不会。任何帮助或见解表示赞赏。

MyQt3DWindow:: MyQt3DWindow(QScreen *screen)
    : Qt3DExtras::Qt3DWindow(screen)
{
    // scene
    Qt3DCore::QEntity *rootEntity = new Qt3DCore::QEntity;
    Qt3DRender::QMaterial *material = new Qt3DExtras::QPhongMaterial(rootEntity);
    Qt3DCore::QEntity *sphereEntity = new Qt3DCore::QEntity(rootEntity);
    Qt3DExtras::QSphereMesh *sphereMesh = new Qt3DExtras::QSphereMesh;
    sphereEntity->addComponent(sphereMesh);
    Qt3DCore::QTransform *sphereTransform = new Qt3DCore::QTransform;
    sphereEntity->addComponent(sphereTransform);
    sphereEntity->addComponent(material);

    // Camera
    Qt3DRender::QCamera *camera = this->camera();
    camera->lens()->setOrthographicProjection(-2, 2, -2, 2, 0.1f, 1000.0f);
    camera->setPosition(QVector3D(0, 0, 40.0f));
    camera->setViewCenter(QVector3D(0, 0, 0));

    // picker
    m_screenRayCaster = new Qt3DRender::QScreenRayCaster(rootEntity);
    m_screenRayCaster->setRunMode(Qt3DRender::QAbstractRayCaster::SingleShot);
    Qt3DRender::QLayer *pickableLayer = new Qt3DRender::QLayer(rootEntity);
    m_screenRayCaster->addLayer(pickableLayer);
    sphereEntity->addComponent(pickableLayer);

    this->setRootEntity(rootEntity);
    this->setGeometry(100, 100, 400, 400);

    // and call the caster after a short delay
    QTimer::singleShot(1000, this, SLOT(testRayCaster()));
}

void MyQt3DWindow::testRayCaster()
{
    m_screenRayCaster->trigger(QPoint(200, 200));
    Qt3DRender::QAbstractRayCaster::Hits hits = m_screenRayCaster->hits();
    qDebug() << "Hits found = " << hits.size() << "\n";
}

class MyQt3DWindow: public Qt3DExtras::Qt3DWindow
{
Q_OBJECT
public:
    MyQt3DWindow(QScreen *screen = nullptr);

public slots:
    void testRayCaster();

private:
    Qt3DRender::QScreenRayCaster *m_screenRayCaster;
};

2 个答案:

答案 0 :(得分:4)

您必须将ray caster作为组件添加到根实体。您还应该将插槽连接到射线投射器的hitsChanged()功能,并从那里显示匹配。这样,您可以确定施法者已经计算出了匹配数。

顺便说一句:如果Qt3D有问题,请签出他们的github存储库并寻找test folder。内部有一个带有手动测试的文件夹,您可以在其中查看Qt3D的大部分功能。

答案 1 :(得分:0)

对于在尝试让屏幕投射器工作时偶然发现此问题的人,除了已接受的答案:

如果要对所有实体进行交集,需要将QLayer设置为根的一个组件,然后设置为递归。 (而不是将其单独设置为子实体,如问题中的 sphereEntity)。

_rayCaster = new QScreenRayCaster(_rootEntity);
_rayCaster->setRunMode(QAbstractRayCaster::SingleShot);

auto pickableLayer = new QLayer(_rootEntity);
pickableLayer->setRecursive(true);
_rootEntity->addComponent(pickableLayer);

_rayCaster->addLayer(pickableLayer);
_rootEntity->addComponent(_rayCaster);
connect(_rayCaster, &QScreenRayCaster::hitsChanged, this, &SceneWidget::onRayCastResult);