-1

I have an issue with simple 2d collision detection with a circle and a rectangle. All the checker does is see if the center of the circle overlaps with any point on the rectangle.

Heres the checker:

boolean overlaps(Circle circle) {   
    for (double i = topLeft.x; i < (topLeft.x + width); i++)
    {
        for (double j = topLeft.y; j < (topLeft.y + height); j++)
        {
            if (circle.center.x == i && circle.center.y == j)
            {

                return true;
            }

        }
    }
return false;
}`

Very simple, and to the point. The error comes into play at the if statement, with my circle.center.x, and/or circle.center.y.

Here is the code for my Circle class:

public class Circle {
Point center;
double radius;
/**
 * Constructor.
 * 
 * @param center  the center Point of the circle
 * @param radius  the radius of the circle
 */
public Circle(Point center, double radius) {
center = this.center;
radius = this.radius;
}

/**
 * Get the current center point of the circle.
 * 
 * @return the center point of the circle
 */
public Point getCenter() {
    return center;
}

/**
 * Set the center point of the circle.
 * 
 * @param center the (new) center point of the circle
 */
public void setCenter(Point center) {
    this.center = center;
}

/**
 * Get the current radius.
 * 
 * @return the current radius
 */
public double getRadius() {
    return radius;
}

/**
 * Set the radius.
 * 
 * @param radius the (new) radius of the circle
 */
public void setRadius(double radius) {
    this.radius = radius;
}

}`

Where am i going wrong? It certainly cannot be an issue with my Point class, as that would mean plenty of other things would've gone wrong by now. Thanks in advance.

1 Answers1

0

Your method should just be:

boolean overlaps( Circle circle )
{
    return topLeft.x <= circle.center.x && circle.center.x <= topLeft.x + width &&
           topLeft.y <= circle.center.y && circle.center.y <= topLeft.y + height;
}
clcto
  • 9,530
  • 20
  • 42
  • Perhaps that would be more proper, however the problem exists in my circle class, as `circle.center.x` returns null, not in the overlap method itself. – GravityCheck Oct 07 '14 at 22:34
  • `circle.center.x` cannot return `null` since it is just a variable. It could be `null`, but only if it is a reference type and not a primitive type. – clcto Oct 07 '14 at 22:41
  • @GravityCheck: Well, what is `null`? – Oliver Charlesworth Oct 07 '14 at 22:43
  • I get a null pointer exception from calling both the x and y values of the center of the circle. – GravityCheck Oct 07 '14 at 22:52
  • @GravityCheck then the center of the circle is null or the circle you are passing to the method itself is null. Use a debugger to figure out why it is null. – clcto Oct 07 '14 at 22:53