JavaFX 如何获取 3D 场景中对象的坐标

标签 java javafx 3d

例如——有这样一段代码

    //create new cylinder
    Cylinder cylinder = new Cylinder(2, 6);
    ...
    //somewhere add transform
    cylinder.getTransforms().add(new Translate(0, -5, 0));
    ...
    //and somewhere i call
    cylinder.setTranslateX(3);
    cylinder.setTranslateY(-2);

因此,圆柱体发生移动,其在场景中的坐标为 {3, -7, 0}

为了获得实际的坐标,我尝试了类似的方法:

    double coordY = 0;

    for(Transform t : cylinder.getTransforms() ){
        coordY += t.getTy();
    }

    coordY += cylinder.getTranslateY();

它有效,但这显然不是最合理的方式......

更新1

正如正确评论的那样fabian

该方法不考虑是否相对于原点以外的点进行旋转

例如:

        Rotate rotate = new Rotate();
        rotate.setAngle(60);

        rotate.setPivotX(2);
        rotate.setPivotY(1);
        rotate.setPivotZ(3);

        cylinder.getTransforms().add(rotate);

在这种情况下,结果将不正确



如何获取该圆柱体或任何其他对象(如 Shape3d 或 MeshView)的真实坐标{x,y,z}

谢谢!

最佳答案

查询Node#getBoundsInParent属性:

The rectangular bounds of this Node which include its transforms. boundsInParent is calculated by taking the local bounds (defined by boundsInLocal) and applying the transform created by setting the following additional variables

  1. transforms ObservableList
  2. scaleX, scaleY, scaleZ
  3. rotate
  4. layoutX, layoutY
  5. translateX, translateY, translateZ

The resulting bounds will be conceptually in the coordinate space of the Node's parent, however the node need not have a parent to calculate these bounds.

Note that this method does not take the node's visibility into account; the computation is based on the geometry of this Node only.

This property will always have a non-null value.

Note that boundsInParent is automatically recomputed whenever the geometry of a node changes, or when any of the following the change: transforms ObservableList, any of the translate, layout or scale variables, or the rotate variable. For this reason, it is an error to bind any of these values in a node to an expression that depends upon this variable. For example, the x or y variables of a shape, or translateX, translateY should never be bound to boundsInParent for the purpose of positioning the node.

您将获得 Bounds对象,它具有查询节点位置和尺寸的方法,包括三维对象。如上述文档中所述,bounds-in-parent 考虑了应用的转换(它是 bounds-in-local + 转换)。当然,这些值都在节点父节点的上下文中。如果您需要不同空间中的坐标,那么您需要转换它们 - Node 类为此提供了许多方法。

关于JavaFX 如何获取 3D 场景中对象的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436151/

相关文章:

java - 手动构建项目是一种好方法

java - 在图表上放置正确的刻度标记

java - SonarQube - 无法连接到 > localhost/0 :0:0:0:0:0:0:1:9000

java - 如何在 JPA2 条件查询中使用多个连接?

javafx - 将旋转的 ImageView 适配到应用程序窗口/场景中

css - 从 JavaFX 中删除所有焦点边框

java - 如何在 JavaFX (fxml) 中制作一个环

javascript - ThreeJScamera.lookAt()没有效果,我做错了什么吗?

python - python/scipy 中 3D 方向的直方图

javascript - 在 Three.js 中移动对象