为了账号安全,请及时绑定邮箱和手机立即绑定

如何使矩形与圆相切

如何使矩形与圆相切

蝴蝶刀刀 2023-06-04 17:36:02
我正在尝试使一个矩形对象围绕一个圆圈,矩形始终与它所围绕的圆相切。我有让它绕着圆圈转的代码,但我不知道如何让它与它相切。到目前为止,这就是它的样子。我正在使用动画计时器,因为我不知道矩形将遵循的完整路径,因为如果我发现有东西阻挡它,它可能会改变。我可以使矩形以平滑的方式绕圆,但我不知道如何使矩形与其相切。 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);   }我知道切线是相邻边 (x) 除以对边 (y),但我不知道如何合并它。
查看完整描述

1 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

我建议使用Rotate转换。这样您只需要设置初始位置和枢轴点,并且可以限制对Rotate.angle属性的更新。


以下示例使用 aTimeline为属性设置动画,但这可以通过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();

}

顺便说一句:您的代码的以下部分看起来很奇怪


double newX = getX() + (radius * Math.cos(Math.toDegrees(angle)));

double newY = getY() + (radius * Math.sin(Math.toDegrees(angle)));

Math.sin并Math.cos期望弧度,而不是度数。您要么需要使用toRadians,要么不需要转换...


查看完整回答
反对 回复 2023-06-04
  • 1 回答
  • 0 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信