2016-01-26 65 views
1

所以我一直在嘗試使用偏航和俯仰的概念,並且我嘗試通過x和y的變化來調整角度。不幸的是,相機的角度有時會超出範圍,並且我一直在爲角度測量添加控件。我究竟做錯了什麼?如何在JavaFX 3D中製作第一人稱相機?

public class Main extends Application { 

    private Group group; 
    private Scene scene; 

    private double oldX; 
    private double oldY; 

    private double newX; 
    private double newY; 

    private double dx; 
    private double dy; 

    private Rotate yaw; 
    private Rotate pitch; 
    private double xSen = 800; 
    private double ySen = 600; 

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

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     group = new Group(); 
     scene = new Scene(group, 800, 600); 

     primaryStage.setScene(scene); 
     primaryStage.show(); 

     yaw = new Rotate(0, Rotate.Y_AXIS); 
     pitch = new Rotate(0, Rotate.X_AXIS); 

     Box box = new Box(5, 5, 5); 
     box.setMaterial(new PhongMaterial(Color.BLUE)); 
     box.setTranslateZ(40); 

     group.getChildren().add(box); 

     PerspectiveCamera camera = new PerspectiveCamera(true); 
     camera.getTransforms().addAll(yaw, pitch); 
     scene.setCamera(camera); 

     xSen = 1; 
     ySen = 1; 
     scene.setOnKeyPressed(event -> { 
      switch (event.getCode()) { 
       case A: 
        xSen -= 1; 
        break; 
       case D: 
        xSen += 1; 
        break; 
       default: 
        break; 
      } 

      System.out.println(xSen + " " + ySen); 
     }); 

     scene.setOnMouseMoved(event -> { 
      oldX = newX; 
      oldY = newY; 
      newX = event.getX(); 
      newY = event.getY(); 
      dx = oldX - newX; 
      dy = oldY - newY; 

      ? 
     }); 
    } 
} 

回答

0

當調用「setOnMouseMoved」時,您的newX和newY未初始化。

  1. oldX和oldY會得到一些值,但不是實際的鼠標位置。
  2. newX和newY獲取屏幕座標的值而不是場景的座標。

  3. 開關新舊計算DELTAX和移動deltaY

  4. 當乘以你的翻譯與步長值。步長越小,立方體移動越慢。

嘗試這樣:

boolean pressed = false; 

    scene.setOnMousePressed((MouseEvent event) -> { 
     pressed = true; 
     newX = event.getSceneX(); 
     newY = event.getSceneY(); 
    }); 

    scene.setOnMouseMoved((MouseEvent event) -> { 
     if(pressed){ 
      oldX = newX; 
      oldY = newY; 
      newX = event.getSceneX(); 
      newY = event.getSceneY(); 
      dx = newX -oldX; 
      dy = newY -oldY; 

      camera.setTranslateX(camera.getTranslateX() - dx*0.1); 
      camera.setTranslateY(camera.getTranslateY() - dy*0.1);  
     }   
    }); 

希望這有助於你。