首页 > 解决方案 > 带有 C++ 和旋转的 QT3D

问题描述

我希望有人可以帮助我解决这个问题。我是使用 QT3D 的新手,我需要使用 QT C++ 制作一个 Qt3D 应用程序来完成一项任务,我遇到的问题是我需要从特定点旋转图形,但它总是从中心点旋转。如何指定旋转是由图中的枢轴之一进行的?我需要它能够模拟钟摆的运动。请帮助告诉我如何解决此问题的人,这是我的代码。

void window::paint(){
    arm1 = new Qt3DExtras::QCylinderMesh();
    arm1->setRadius(0.5);
    arm1->setLength(3);

    arm1Transform = new Qt3DCore::QTransform();
    arm1Transform->setTranslation(QVector3D(-3, 3, 0));
    arm1Transform->setScale(1.5f);

    Qt3DExtras::QPhongMaterial *arm1Material = new Qt3DExtras::QPhongMaterial();
    arm1Material->setDiffuse(Qt::red);

    arm1Entity = new Qt3DCore::QEntity(rootEntity);
    arm1Entity->addComponent(arm1);
    arm1Entity->addComponent(arm1Material);
    arm1Entity->addComponent(arm1Transform);
}

void window::on_pushButton_clicked(){
    arm1Transform->setRotation(QQuaternion::fromAxisAndAngle(QVector3D(1.0f, 0.0f, 0.0f), angle++));
}

提前致谢。

标签: c++rotationqt3d

解决方案


您可以使arm1Entity成为新 QEntity 的子级。这个新的 QEntity 将定位在您要旋转的位置。因此,如果您旋转新的 QEntity,他的子arm1Entity将从新 QEntity 的位置旋转。

编辑代码(未测试):

void window::paint(){
    arm1PivotEntity = new Qt3DCore::QEntity(rootEntity);
    arm1PivotTransform = new Qt3DCore::QTransform(arm1PivotEntity);
    arm1PivotTransform->setTranslation(QVector3D(/*desired pivot position*/));
    arm1PivotEntity->addComponent(arm1PivotTransform);

    arm1 = new Qt3DExtras::QCylinderMesh();
    arm1->setRadius(0.5);
    arm1->setLength(3);

    arm1Transform = new Qt3DCore::QTransform();
    // as arm1 is now child of arm1 pivot, you need to set the relative position
    arm1Transform->setTranslation(QVector3D(/*relative position to arm1pivot position*/)); 
    arm1Transform->setScale(1.5f);

    Qt3DExtras::QPhongMaterial *arm1Material = new Qt3DExtras::QPhongMaterial();
    arm1Material->setDiffuse(Qt::red);

    // made arm1 child of arm1pivot so it will inherits its rotation
    arm1Entity = new Qt3DCore::QEntity(arm1PivotEntity); 
    arm1Entity->addComponent(arm1);
    arm1Entity->addComponent(arm1Material);
    arm1Entity->addComponent(arm1Transform);
}

void window::on_pushButton_clicked(){
    arm1PivotTransform->setRotation(angle++));
}

推荐阅读