Game Development Reference
In-Depth Information
public Circle( float x, float y, float radius) {
this .center.set(x,y);
this .radius = radius;
}
}
We store the center as a Vector2 and the radius as a simple float. How can we check whether
two circles overlap? Take a look at Figure 8 - 13 .
Figure 8-13. Two circles overlapping (left), and two circles not overlapping (right)
It's very simple and computationally efficient. All we need to do is figure out the distance
between the two centers. If the distance is greater than the sum of the two radii, then we know
the two circles do not overlap. In code, this will appear as follows:
public boolean overlapCircles(Circle c1, Circle c2) {
float distance = c1.center.dist(c2.center);
return distance <= c1.radius + c2.radius;
}
First, we measure the distance between the two centers, and then check to see if the distance is
smaller or equal to the sum of the radii.
We have to take a square root in the Vector2.dist() method. This is unfortunate, as taking the
square root is a costly operation. Can we make this faster? Yes, we can—all we need to do is
reformulate your condition:
(
)
sqrt dist.x
×
dist.x
+
dist.y
×
dist.y
<=
radius1
+
radius2
We can get rid of the square root by exponentiating both sides of the inequality, as follows:
(
) (
)
dist.x
×
dist.x
+
dist.y
×
dist.y
<=
radius1
+
radius2
×
radius1
+
radius2
We trade the square root for another addition and multiplication on the right side. This is a
lot better. Now we can create a Vector2.distSquared() function that will return the squared
distance between two vectors:
public float distSquared(Vector2 other) {
float distX = this .x - other.x;
float distY = this .y - other.y;
return distX * distX + distY * distY;
}
Search WWH ::




Custom Search