球如何将方向指向击中的球?

时间:2019-05-02 14:16:48

标签: java swing awt java-2d

我正在尝试创建一个包含2个球的窗口,当将一个击球移动到另一个击球时,它也应该移动。但是当我尝试时,移动的那一刻就停止了。你有什么建议吗?

public class BallPanel extends JLabel implements ActionListener {
    double s =30;
    double Vx = 5, Vy=5;

    double V = 10;
    Ellipse2D.Double ball = new Ellipse2D.Double (100,200,s,s);
    Ellipse2D.Double ball2 = new Ellipse2D.Double (120,100,s,s);
    Timer t = new Timer(10,this);

    BallPanel() {
        t.start();
    }

    @Override
    public void actionPerformed(ActionEvent e ) {
        ball.x += Vx;
        ball.y += Vy;

        ball2.x += 0;
        ball2.y += 0;

        if (ball.x < 0 || ball.x > getWidth() - ball.width) Vx = -Vx;

        if (ball.y < 0 || ball.y > getHeight() - ball.height) Vy = -Vy;

        double dx = ball.getCenterX() - ball2.getCenterX();
        double dy = ball.getCenterY() - ball2.getCenterY() ;

        if (dx*dx + dy*dy < ball.width * ball2.width) t.stop();
        double Ux = ball2.x - ball.x;
        double Uy = ball2.y - ball.y;

        repaint();
    }
}

0 个答案:

没有答案