如何仅在红色圆圈路径上限制蓝色圆圈的运动(由于鼠标拖动)?我应该使用极坐标吗? (x = r cos(θ),y = r sin(θ))?
我创建的代码到现在为止让我在整个舞台上拖动蓝点。我希望蓝点的中心跟随红色圆圈。
package circlemouse;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class CircleMouse extends Application {
private double initY;
private double dragAnchorY;
private double initX;
private double dragAnchorX;
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Scene scene = new Scene(pane, 500, 500);
primaryStage.setResizable(false);
//stage center
double x0 = pane.getWidth() / 2.0;
double y0 = pane.getHeight() / 2.0;
Line horizontalLine = new Line(0.0, y0, 2.0 * x0, y0);
Line vertical = new Line(x0, 0.0, x0, 2.0 * y0);
//red circle (path of point)
double r = 100.0;
Circle c = new Circle(x0, y0, r);
c.setFill(null);
c.setStroke(Color.RED);
//the point
double pointRadius = 15.0;
Circle point = new Circle(x0 + r, y0, pointRadius);
point.setFill(Color.BLUE);
point.setOnMousePressed((MouseEvent me) -> {
initY = point.getCenterY();
dragAnchorY = me.getSceneY();
initX = point.getCenterX();
dragAnchorX = me.getSceneX();
});
point.setOnMouseDragged((MouseEvent me) -> {
double dragY = me.getSceneY() - dragAnchorY;
double newY = initY + dragY;
point.setCenterY(newY);
double dragX = me.getSceneX() - dragAnchorX;
double newX = initX + dragX;
point.setCenterX(newX);
});
pane.getChildren().addAll(horizontalLine, vertical, c, point);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:2)
如果从红色圆圈的中心到鼠标所在的位置画一条线,然后从红色圆圈的中心画一条线到你想要的位置,它们显然是在同一个方向,从红色圆心到您想要的点的直线长度就是直线的半径。
因此,在矢量术语中,从圆心到新点位置的矢量是圆的半径乘以从圆心到鼠标的方向上的单位矢量。
Point2D
API允许您将Point2D
解释为向量,并且具有用于计算单位向量(normalize()
),乘以标量,添加和减去其他向量的有用方法等等。
所以:
point.setOnMouseDragged((MouseEvent me) -> {
Point2D redCenter = new Point2D(c.getCenterX(), c.getCenterY());
Point2D mouse = new Point2D(me.getX(), me.getY());
Point2D centerToMouse = mouse.subtract(redCenter);
Point2D centerToNewPoint = centerToMouse.normalize().multiply(c.getRadius());
Point2D newPoint = centerToNewPoint.add(redCenter);
point.setCenterX(newPoint.getX());
point.setCenterY(newPoint.getY());
});