我试图使一个矩形对象围绕一个圆旋转,而矩形始终与它所围绕的圆相切。我有使它绕圈旋转的代码,但我看不出如何使其与切线相切。到目前为止是这样。
我使用的是动画计时器,因为我不知道矩形会遵循的完整路径,因为如果我发现矩形会改变它,它就会改变。我可以使矩形以平滑的方式绕圆旋转,但是我不知道如何使矩形切线。
public void moveInCircle(double radius)
{
double newX = getX() + (radius * Math.cos(Math.toDegrees(angle)));
double newY = getY() + (radius * Math.sin(Math.toDegrees(angle)));
vehicle.setTranslateX(newX);
vehicle.setTranslateY(newY);
}
Run Code Online (Sandbox Code Playgroud)
我知道切线将是相邻的边(x)除以相对的边(y),但我不知道如何将其合并。
我建议使用Rotate转换。这样,您只需要设置初始位置和枢轴点即可,并且可以限制对Rotate.angle属性的更新。
下面的示例使用a Timeline来为属性设置动画,但这可以moveCircle通过使用rotate.setAngle(angleDegrees);以下方法从方法中轻松完成:
@Override
public void start(Stage primaryStage) {
Pane root = new Pane();
root.setMinSize(500, 500);
final double radius = 150;
final double centerX = 250;
final double centerY = 250;
final double height = 40;
Circle circle = new Circle(centerX, centerY, radius, null);
circle.setStroke(Color.BLACK);
// rect starts at the rightmost point of the circle touching it with the left midpoint
Rectangle rect = new Rectangle(centerX + radius, centerY - height / 2, 10, height);
rect.setFill(Color.RED);
Rotate rotate = new Rotate(0, centerX, centerY); // pivot point matches center of circle
rect.getTransforms().add(rotate);
// animate one rotation per 5 sec
Timeline animation = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(rotate.angleProperty(), 0d)),
new KeyFrame(Duration.seconds(5), new KeyValue(rotate.angleProperty(), 360d)));
animation.setCycleCount(Animation.INDEFINITE);
animation.play();
root.getChildren().addAll(circle, rect);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句:您的代码的以下部分似乎很奇怪
double newX = getX() + (radius * Math.cos(Math.toDegrees(angle)));
double newY = getY() + (radius * Math.sin(Math.toDegrees(angle)));
Run Code Online (Sandbox Code Playgroud)
Math.sin并Math.cos期望弧度,而不是度数。您要么需要使用,要么不需要toRadians转换...