JavaFX 3D 可视化编程二
上一篇介绍了基于JavaFX 3D的物体缩放,分别是通过键盘的操作事件,前后移动物体和前后移动相机。这一篇介绍物体的旋转。
主要是在Group的基础上新建了个SmartGroup类,给他添加了可以进行旋转的函数。新建类代码如下
class SmartGroup extends Group{
Rotate r;
Transform t = new Rotate();
void rotateByX(int ang){
r=new Rotate(ang, Rotate.X_AXIS);
t = t.createConcatenation(r);
this.getTransforms().clear();
this.getTransforms().addAll(t);
}
void rotateByY(int ang){
r=new Rotate(ang, Rotate.Y_AXIS);
t = t.createConcatenation(r);
this.getTransforms().clear();
this.getTransforms().addAll(t);
}
}
整体代码如下
package chapt3;
import javafx.application.Application;
import javafx.geometry.Point3D;
import javafx.scene.Camera;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Sphere;
import javafx.scene.shape.Box;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Transform;
import javafx.stage.Stage;
public class Rotation3D extends Application {
private static final int WIDTH=1400;
private static final int HEIGHT=800;
@Override
public void start(Stage primaryStage) throws Exception{
Box box = new Box( 100, 20, 50);
SmartGroup group = new SmartGroup();
group.getChildren().add(box);
Camera camera = new PerspectiveCamera();
Scene scene =new Scene(group, WIDTH, HEIGHT);
scene.setFill(Color.SILVER);
scene.setCamera(camera);
group.translateXProperty().set(WIDTH/2);
group.translateYProperty().set(HEIGHT/2);
group.translateZProperty().set(-1200);
//Transform transform = new Rotate(65, new Point3D(1,0,0));
//box.getTransforms().add(transform);
primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, event->{
switch (event.getCode()){
case W:
group.translateZProperty().set(group.getTranslateZ()+50);
break;
case S:
group.translateZProperty().set(group.getTranslateZ()-50);
break;
case Q:
group.rotateByX(10);
break;
case E:
group.rotateByX(-10);
break;
case A:
group.rotateByY(10);
break;
case D:
group.rotateByY(-10);
break;
}
});
primaryStage.setTitle("Camera3D");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
class SmartGroup extends Group{
Rotate r;
Transform t = new Rotate();
void rotateByX(int ang){
r=new Rotate(ang, Rotate.X_AXIS);
t = t.createConcatenation(r);
this.getTransforms().clear();
this.getTransforms().addAll(t);
}
void rotateByY(int ang){
r=new Rotate(ang, Rotate.Y_AXIS);
t = t.createConcatenation(r);
this.getTransforms().clear();
this.getTransforms().addAll(t);
}
}
}
效果如下