为什么球会粘住而不是发生碰撞?

时间:2019-05-12 15:03:18

标签: java

我遇到的问题是,有时两个球碰撞时,它们会粘在一起,重叠得很小。它们不会自行破裂,但是如果有另一个球撞击它们,它们可能会散开。

这是我的碰撞检测和解决代码:

public void updateBallPosition() {
    ball.x+=Vx;
    ball.y+=Vy;

    ball2.x+=Vx2;
    ball2.y+=Vy2;

    if(ball.x<0 || ball.x>getWidth()-sz) Vx=-Vx;
    if(ball.y<0 || ball.y>getHeight()-sz) Vy=-Vy;

    if(ball2.x<0 || ball2.x>getWidth()-sz) Vx2=-Vx2;
    if(ball2.y<0 || ball2.y>getHeight()-sz) Vy2=-Vy2;

    //Vx = Vx*0.99;
    //Vy = Vy*0.99;
    double dx = ball2.x - ball.x;
    double dy = ball2.y - ball.y;

    double Umag = Math.hypot(dx, dy);

    if(Umag <= ball.width)
    {

        double VrMag = (Vx*dx + Vy*dy )/ Umag;
        double Vrx = VrMag * dx / Umag;
        double Vry = VrMag * dy / Umag;

        double Vtx = Vx - Vrx;
        double Vty = Vy - Vry;


        Vx = Vtx;
        Vy = Vty;
        Vx2 = Vrx;
        Vy2 = Vry;
        //Vx=0;Vy=0;
    }


    //if(Vx*Vx + Vy*Vy < 1 )
    //  t.stop();
    repaint();

}

@Override
public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub
    if(!t.isRunning()) {
        double x1 = e.getX();
        double y1 = e.getY();
        double x2 = ball.x + ball.width/2;
        double y2 = ball.y + ball.height/2;
        double dx = x2-x1;
        double dy = y2-y1;
        Vx = V*dx/Math.sqrt(dx*dx+dy*dy);
        Vy = V*dy/Math.sqrt(dx*dx+dy*dy);
        Vx = -2;
        Vy = -2;
        t.start();
    }
}

0 个答案:

没有答案