为什么添加SubScene会更改JavFX中的localToScreen函数输出?

时间:2020-08-07 07:08:29

标签: java javafx javafx-3d

我正在尝试使用JavaFX开发具有多个视口的工具,我认为做到这一点的最佳方法是使用SubScenes。我的一项要求是能够知道场景中给定平面上的哪个位置对应于鼠标单击的像素。我以为我可以使用Node.localToScreen()和Node.screenToLocal()函数来完成此操作,但是在添加SubScene时我得到了不同的值,尽管没有其他改变。

下面是一个示例,其中使用withSubScene = false运行代码,控制台显示:

Point2D [x = 996.0, y = 514.8333400189878]
Point2D [x = 117.98005476276654, y = 514.8333400189878]

并以withSubScene = true运行,控制台显示:

Point2D [x = 997.0, y = 529.3333400189878]
Point2D [x = 64.91937872905163, y = 529.3333400189878]

当摄像机位于同一位置并看着同一物体时,为什么这些值会不同?

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class ScreenToLocalTest extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        // Change this variable to swap to adding a SubScene
        boolean withSubScene = false;

        // Set the stage to be the same size each time
        primaryStage.setWidth(1000);
        primaryStage.setHeight(500);

        Group root = new Group();
        Scene rootScene = new Scene(root);

        // Create out camera
        Camera camera = new PerspectiveCamera(true);
        camera.setTranslateZ(-1000);
        camera.setNearClip(1);
        camera.setFarClip(10000);

        Group groupToAddRectangle;

        if(withSubScene) {
            Group sceneRoot = new Group();
            SubScene subScene = new SubScene(sceneRoot, primaryStage.getWidth(), primaryStage.getHeight());
            root.getChildren().add(subScene);

            subScene.setCamera(camera);

            groupToAddRectangle = sceneRoot;
        } else {
            rootScene.setCamera(camera);

            groupToAddRectangle = root;
        }

        Rectangle rectangle = new Rectangle(1000, 300, Color.ALICEBLUE);
        groupToAddRectangle.getChildren().add(rectangle);
        rectangle.setTranslateZ(1);

        root.setOnMouseMoved(event-> {
            System.out.println(rectangle.screenToLocal(event.getScreenX(), event.getScreenY()));
        });

        primaryStage.setScene(rootScene);
        primaryStage.show();


        System.out.println(rectangle.localToScreen(0, 0));
        rectangle.translateXProperty().set(-1000);
        System.out.println(rectangle.localToScreen(0, 0));
    }

    public static void main(String[] args) {
        launch(args);
    }
}

0 个答案:

没有答案