I am trying to make a rectangle object to go around a circle, with the rectangle always tangent to the circle where it is going around. I have the code that will make it go around the circle, but I don't see how to make it tangent to it. This is how it looks so far.
I am using an animation timer, since I don't know the full path that the rectangle will follow as it can change if I it finds something blocking it. I can make the rectangle go around the circle in a smooth way, but I don't know how to make the rectangle tangent to it.
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);
}
I know that the tangent will be the adjacent side(x) divided by the opposite side (y), but I don't understand how to incorporate it.
I recommend using a Rotate
transform. This way you only need to set the initial position and the pivot point and can restrict the updates to the Rotate.angle
property.
The following example uses a Timeline
to animate the property, but this could easily be done from the moveCircle
method by using 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();
}
Btw: the following part of your code seems odd
double newX = getX() + (radius * Math.cos(Math.toDegrees(angle)));
double newY = getY() + (radius * Math.sin(Math.toDegrees(angle)));
Math.sin
and Math.cos
expect radians, not degree. You either need to use toRadians
or don't require a conversion...