Game Development Reference
In-Depth Information
We should also add a second distSquared() method that takes two floats (x and y) instead of a
vector.
The overlapCircles() method then becomes the following:
public boolean overlapCircles(Circle c1, Circle c2) {
float distance = c1.center.distSquared(c2.center);
float radiusSum = c1.radius + c2.radius;
return distance <= radiusSum * radiusSum;
}
Rectangle Collision
For rectangle collision, we first need a class that can represent a rectangle. As previously
mentioned, we want a rectangle to be defined by its lower-left corner position, plus its width and
height. Listing 8-5 does just that.
Listing 8-5. Rectangle.java, a Rectangle Class
package com.badlogic.androidgames.framework.math;
public class Rectangle {
public final Vector2 lowerLeft;
public float width, height;
public Rectangle( float x, float y, float width, float height) {
this .lowerLeft = new Vector2(x,y);
this .width = width;
this .height = height;
}
}
We store the lower-left corner's position in a Vector2 and the width and height in two floats. How
can we check whether two rectangles overlap? Figure 8-14 should give you a hint.
Figure 8-14. Lots of overlapping and nonoverlapping rectangles
The first two cases of partial overlap (left) and nonoverlap (center) are easy. The case on the
right is a surprise. A rectangle can, of course, be completely contained in another rectangle. This
can happen in the case of circles, as well. However, our circle overlap test will return the correct
result if one circle is contained in the other circle.
 
Search WWH ::




Custom Search