Search code examples
java2dcollisiondetection

Trouble with java 2D collision detection


I'm in the process of making a program in Java that models the gravitational attraction between 2 objects. I've simplified it by using 2 balls (one fixed and one free to move) and have figured out how to program the equations too. I want the balls to reset if they collide with one another, to prevent confusion, yet upon programming a collision detection method it does not seem to work the way I want it to. For example, direct collisions are correctly detected but when the free ball curves into the fixed ball it clips right through.

I've created a checkIfCollision method within my Ball class:

public boolean checkIfCollided(Ball ball2)
    {
        double xCenter1 = getxCoord()+getRadius();
        double yCenter1 = getyCoord()+getRadius();  

        double xCenter2 = ball2.getxCoord()+ball2.getRadius();
        double yCenter2 = ball2.getyCoord()+ball2.getRadius();

        double xDiff = (xCenter2-xCenter1);
        double yDiff = (yCenter2-yCenter1);

        double sqrRadius = (getRadius()*getRadius())+(ball2.getRadius()*ball2.getRadius());

        double sqrDistance = (((xDiff*xDiff) + (yDiff*yDiff)));


        if (sqrDistance <= (sqrRadius))
        {
            return true;
        }           
        return false;           
    }

I have a timer looping within my main program, here is where I call upon the method

public void actionPerformed(ActionEvent e) 
{
    if (e.getActionCommand() == "myTimer")
    {
        if (player.checkIfCollided(planet))
        {
            reset();
        }
        Vector2D radius = new Vector2D((float)(planet.getxCoord()-player.getxCoord()), (float) (planet.getyCoord()-player.getyCoord()));
        if (ballIsReleased)
        {   
            float forceFactor = (float) ((G * player.getMass() * planet.getMass())/(radius.magnitude()*radius.magnitude()))*300;
            player.setAccelleration(new Vector2D((float)(planet.getxCoord()-player.getxCoord())/500, (float)(planet.getyCoord()-player.getyCoord())/500), forceFactor);
            player.move();  
        }
        if (player.checkIfCollided(planet))
        {
            reset();
        }
        repaint();      
    }
}

Can anyone see where I've gone wrong? I've been checking where the center of the balls is over and over but it still doesn't seem to work the way I want it to.


Solution

  • I think your equations are wrong. You are comparing the squared distance between the centers to the sum of the squares of the radii. You need to compare it to the square of the sum of the radii: (r1 + r2)2 instead of r12 + r22.

    Also, I don't know what getxCoord and getyCoord return, but it seems an odd way to represent a sphere to define the location by (xCenter - r, yCenter - r) (which it seems you are doing, since you're adding the radius to get to the center).