You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FXML文件中为启用3D的Subscene配置静态透视相机

将Camera和MeshView配置到FXML中的实现方法

直接修改你的FXML文件,替换根容器并添加相机、3D模型的定义即可,具体步骤如下:

1. 修改FXML结构

把原来的<Region />替换为<Group />(Region是2D容器,不适合承载3D节点),然后在SubScene中直接配置Camera,同时在Group下添加MeshView。完整代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.SubScene?>
<?import javafx.scene.SceneAntialiasing?>
<?import javafx.scene.Group?>
<?import javafx.scene.PerspectiveCamera?>
<?import javafx.scene.shape.Box?>
<?import javafx.scene.shape.MeshView?>
<?import javafx.scene.paint.PhongMaterial?>
<?import javafx.scene.paint.Color?>

<SubScene fx:id="viewer3d" depthBuffer="true" fill="#3389de" height="600.0" width="600.0">
    <root>
        <Group>
            <!-- 示例3D模型:Box,可替换为你需要的MeshView -->
            <MeshView fx:id="cubeMesh">
                <mesh>
                    <Box width="100" height="100" depth="100" />
                </mesh>
                <material>
                    <PhongMaterial diffuseColor="#ff4081" specularColor="#ffffff" />
                </material>
                <!-- 调整模型位置,让相机能看到 -->
                <translateZ> -200 </translateZ>
            </MeshView>
        </Group>
    </root>
    <antiAliasing>
        <SceneAntialiasing fx:constant="BALANCED" />
    </antiAliasing>
    <!-- 配置透视相机,绑定到SubScene的camera属性 -->
    <camera>
        <PerspectiveCamera 
            fieldOfView="60" 
            nearClip="0.1" 
            farClip="1000" 
            fixedEyeAtCameraZero="true"
            translateZ="100" />
    </camera>
</SubScene>

2. 关键说明

  • 根容器替换:Group是3D场景的标准根容器,支持3D节点的层级渲染,而Region是2D布局组件,无法正确处理3D空间关系。
  • Camera配置:通过SubScene的<camera>标签直接定义PerspectiveCamera(3D场景首选的透视相机),核心参数:
    • fieldOfView:控制视野角度,数值越大视野越广
    • nearClip/farClip:设置相机的渲染范围,超出该范围的对象会被裁剪
    • fixedEyeAtCameraZero:固定相机在世界坐标系原点,简化初始定位
    • 可以通过translateX/Y/Z调整相机位置,让模型处于视野内
  • MeshView定义:在Group下添加MeshView,指定mesh(内置几何体如Box/Sphere,或自定义Mesh)和材质(PhongMaterial支持光影效果),通过translateX/Y/Z调整模型位置,确保相机能捕捉到。

3. 控制器简化

原来运行时创建Camera和MeshView的代码可以完全删除,控制器只需通过@FXML注入需要操作的节点即可:

import javafx.fxml.FXML;
import javafx.scene.SubScene;
import javafx.scene.shape.MeshView;

public class Viewer3dController {
    @FXML
    private SubScene viewer3d;
    @FXML
    private MeshView cubeMesh; // 如果需要操作模型,注入对应的fx:id

    public void initialize() {
        // 这里可以做其他初始化操作,比如调整模型旋转、材质等
        cubeMesh.setRotate(45);
    }
}

内容的提问来源于stack exchange,提问作者Giovanni Contreras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:41