我在创建一个简单的太阳/地球类动画时遇到了麻烦。
在下面的示例中,圆应该围绕矩形动态观察。
为此,我创建了一个新组,附加偏移为0的矩形和偏移量为50的圆。
现在,当组被旋转时,我认为矩形应该围绕自己旋转,圆圈应该围绕矩形旋转。
但这两个形状似乎都有一个偏移量,并围绕一个看不见的中心旋转。
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// create root node
Group root = new Group();
Scene scene = new Scene(root, 640, 400);
primaryStage.setScene(scene);
// translate root node to center of the screen
root.setTranslateX(320);
root.setTranslateY(200);
// create scene
createScene(root);
primaryStage.show();
}
private void createScene(Group root) {
Group branch = new Group();
root.getChildren().add(branch);
// create a recangle, which will be added to the branch
Rectangle r = new Rectangle(40, 20);
branch.getChildren().add(r);
// circle should orbit around the rectangle
Circle c = new Circle(10);
branch.getChildren().add(c);
c.setTranslateY(-50);
// rotate the branch
Timeline rot = new Timeline();
rot.setCycleCount(Timeline.INDEFINITE);
rot.setRate(1);
rot.getKeyFrames().addAll(
new KeyFrame(Duration.ZERO, new KeyValue(
branch.rotateProperty(), 0)),
new KeyFrame(Duration.seconds(5), new KeyValue(branch
.rotateProperty(), 360)));
rot.playFromStart();
}
public static void main(String[] args) {
launch(args);
}
}发布于 2012-03-28 22:33:02
请注意,任何对象的旋转都会围绕其中心发生。解决问题的最简单方法是使用StackPane而不是组。默认情况下,StackPane会将所有对象放在其中心。
private void createScene(Group root) {
Pane branch = new StackPane();
root.getChildren().add(branch);https://stackoverflow.com/questions/9908402
复制相似问题