Qt3D 围绕网格旋转相机

dan*_*m87 5 c++ qt qml qt3d

我最近开始学习 Qt/QML/C++ 并尝试构建一个非常基本的 3D 场景来围绕网格对象旋转相机。

我发现很难遵循这些示例,而且我发现文档没有提供任何有用的说明。那里似乎也没有很多教程,也许我找错了地方。

主程序

#include <Qt3DQuickExtras/qt3dquickwindow.h>
#include <Qt3DQuick/QQmlAspectEngine>

#include <QGuiApplication>
#include <QtQml>

int main(int argc, char **argv)
{
    QGuiApplication app(argc, argv);
    Qt3DExtras::Quick::Qt3DQuickWindow view;

    // Expose the window as a context property so we can set the aspect ratio
    view.engine()->qmlEngine()->rootContext()->setContextProperty("_window", &view);
    view.setSource(QUrl("qrc:/main.qml"));
    view.setWidth(800);
    view.setHeight(600);
    view.show();

    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)

主文件

import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Input 2.0
import Qt3D.Extras 2.0

Entity {
    id: sceneRoot

    Camera {
        id: camera
        projectionType: CameraLens.PerspectiveProjection
        fieldOfView: 25
        aspectRatio: _window.width / _window.height
        nearPlane : 0.1
        farPlane : 1000.0
        position: Qt.vector3d( 0, 0.0, 20.0 )
        upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
        viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
    }

    OrbitCameraController {
        camera: camera
    }

    components: [
        RenderSettings {
            activeFrameGraph: ForwardRenderer {
                clearColor: Qt.rgba(0, 0.5, 1, 1)
                camera: camera
            }
        },
        InputSettings { }
    ]

    PhongMaterial {
        id: carMaterial
    }

    Mesh {
        id: carMesh
        source: "resources/aventador.obj"
    }

    Entity {
        id: carEntity
        components: [ carMesh, carMaterial ]
    }
}
Run Code Online (Sandbox Code Playgroud)

如何让相机围绕网格物体旋转?

use*_*011 2

OrbitCameraController 允许沿着轨道路径移动相机。要使其围绕网格旋转,您可以将相机的 viewCenter 设置为网格的位置(包含网格的实体的变换的平移)并使用键盘/鼠标来旋转它。

所以添加:

Transform{
        id: carTransform
        translation: Qt.vector3d(5.0, 5.0, 5.0) //random values, choose your own
}
Run Code Online (Sandbox Code Playgroud)

并将变换添加到实体的组件中。将相机的viewCenter更改为

viewCenter: carTransform.translation
Run Code Online (Sandbox Code Playgroud)