本页内容

Qt Quick 3D - 实例化渲染示例

演示如何在Qt Quick 3D 中实现实例化渲染。

展示实例化渲染效果的太空场景,包含小行星带和两艘飞船

本示例展示了如何使用基础 QML API 进行实例化渲染。

飞船和小行星模型是使用Blender 3D建模工具创建的,并通过balsam导入。

随机实例化

我们使用RandomInstancing 生成一个随机表来定义小行星带:

RandomInstancing {
    id: randomInstancing
    instanceCount: 1500

    position: InstanceRange {
        from: Qt.vector3d(-300, -200, -500)
        to: Qt.vector3d(300, 200, 200)
    }
    scale: InstanceRange {
        from: Qt.vector3d(1, 1, 1)
        to: Qt.vector3d(10, 10, 10)
        proportional: true
    }
    rotation: InstanceRange {
        from: Qt.vector3d(0, 0, 0)
        to: Qt.vector3d(360, 360, 360)
    }
    color: InstanceRange {
        from: "grey"
        to: "white"
        proportional: true
    }

    randomSeed: 2021
}

位置和旋转允许自由变化。缩放设置为各方向均匀,颜色为灰度。这是通过设置proportional 属性实现的。

飞船通过InstanceList 手动放置:

InstanceListEntry {
    id: redShip
    eulerRotation: Qt.vector3d(0, 180, 0)
    color: "red"
    PropertyAnimation on position {
        from: Qt.vector3d(50, 10, 100)
        to: Qt.vector3d(-70, 10, 100)
        duration: 8000
    }
}

InstanceListEntry {
    id: greenShip
    position: Qt.vector3d(0, 0, -60)
    eulerRotation: Qt.vector3d(-10, 0, 30)
    color: "green"
}

InstanceListEntry {
    id: blueShip
    position: Qt.vector3d(-100, -100, 0)
    color: "blue"
}

InstanceList {
    id: manualInstancing
    instances: [ redShip, greenShip, blueShip ]
}

InstanceListEntry 的属性可绑定:在此我们对红色飞船进行动画处理,使其横穿摄像机的路径。

最后,我们将实例化表应用到对象上:

Asteroid {
    instancing: randomInstancing
    NumberAnimation on eulerRotation.x {
        from: 0
        to: 360
        duration: 11000
        loops: Animation.Infinite
    }
}

SimpleSpaceship {
    instancing: manualInstancing
}

通过动画控制小行星模型的旋转,所有实例都会随之旋转,而无需更改实例表的内容。由于小行星实例具有随机的旋转角度,因此所有小行星都会围绕不同的轴旋转。

示例项目 @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.