圆到圆矢量变换

时间:2019-03-22 16:04:20

标签: java javafx

我有一个程序,您可以使用JavaFX在场景上拖放圆圈。我不希望圆彼此碰撞,所以我添加了一个碰撞算法来检查它是否可以正常工作。让我感到困惑的是我以后想要做的事情。

如果两个圆重叠,我想在两个圆的中间做一个向量,然后将移动的圆沿向量的方向变换,直到不再重叠。

Mouse dropped. Detected collision and transform second circle.

            for (Stone stn:getCurrentScenario().getStones()) {
                if (stn.circle == circle) continue;

                double x1 = stn.circle.getTranslateX();
                double y1 = stn.circle.getTranslateY();
                double r1 = stn.circle.getRadius()+stn.circle.getStrokeWidth();

                double x2 = circle.getTranslateX();
                double y2 = circle.getTranslateY();
                double r2 = circle.getRadius();

                double distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
                double radSumSq = (r1 + r2) * (r1 + r2);


                if (!(distSq != radSumSq && distSq > radSumSq)) {
                    System.out.println("Collision.");
                    // Transform "circle".

                }

            }

1 个答案:

答案 0 :(得分:0)

我最终跳过了矢量概念,而是转个角度。如果其他人遇到类似问题,将保留标题:

    double newX = circle.getTranslateX();
    double newY = circle.getTranslateY();


    for (Stone stn:getCurrentScenario().getStones()) {
        if (stn.circle == circle) continue;

        double x1 = stn.circle.getTranslateX();
        double y1 = stn.circle.getTranslateY();
        double r1 = stn.circle.getRadius()+stn.circle.getStrokeWidth();

        double x2 = newX;
        double y2 = newY;
        double r2 = circle.getRadius();

        double distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
        double radSumSq = (r1 + r2) * (r1 + r2);


        if (!(distSq != radSumSq && distSq > radSumSq)) {
            double angle = Math.atan2(x1-x2,y1-y2);
            newX = x1 - Math.sin(angle) * (circle.getRadius() + circle.getStrokeWidth() + stn.circle.getRadius() + .01);
            newY = y1 - Math.cos(angle) * (circle.getRadius() + circle.getStrokeWidth() + stn.circle.getRadius() + .01);



        }
    }
    for (Stone stn:getCurrentScenario().getStones()) {
        if (stn.circle == circle) continue;
        double x1 = stn.circle.getTranslateX();
        double y1 = stn.circle.getTranslateY();
        double r1 = stn.circle.getRadius()+stn.circle.getStrokeWidth();

        double x2 = newX;
        double y2 = newY;
        double r2 = circle.getRadius();

        double distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
        double radSumSq = (r1 + r2) * (r1 + r2);

        if (!(distSq != radSumSq && distSq > radSumSq)) {
            newX = oldX;
            newY = oldY;
            break;
        }
    }

    circle.setTranslateX(newX);
    circle.setTranslateY(newY);

我做了那段代码只是为了确保它能按预期工作。现在要改进它。