Game Development Reference
In-Depth Information
These are the most important methods for drawing shapes in the
Canvas
class, but we need more.
For example, for a polygon-based game, a basic technique is to inscribe shapes within rectangles. In this
way, operations such as collision detection and rendering can be applied. Thus, we need three basic
shapes for our Asteroids game that are missing from the Android API: a rectangle, a polygon, and a
polygon sprite.
■
Tip
The Android API defines the classes
Rect
and
RectF
for rectangles, but it does not define polygons or
polygon sprites.
Understanding the Caveats of Drawing Rectangles
From the drawing methods in the previous section, we could use
Canvas.drawLines
to draw our polygons
directly. However, we also need extra functionally:
A way to detect if a polygon is inside another in the (X, Y) coordinate system,
which is necessary to detect collisions within the game
•
A way to assign style and color to the polygon
Thus, using
Canvas.drawLines
is insufficient to manipulate polygons directly. We need a more
elegant solution; we need to create
Rectangle
,
Polygon
, and
PolygonSprite
classes.
Android already has the classes
Rect
and
RectF
that could be reused. Nevertheless these classes lack
the functionality to check if the rectangle is inscribed within another (a critical requirement for
Asteroids).
Listing 4-1 shows the class
Rectangle
capable of remembering its (X, Y) coordinates plus width and
height. It can also check if its bounds contain or are inside another rectangle. As a matter of fact this
code is taken from the Java SE
java.awt.Rectangle
class (taking advantage of the high portability of
Java).
The
Rectangle
class in Listing 4-1 is the basis for the polygon sprite we need for Asteroids.
•
Listing 4-1.
The Rectangle Class Used by Polygon
package ch04.common;
public class Rectangle {
public int x;
public int y;
public int width;
public int height;
public Rectangle() {
this(0, 0, 0, 0);
}