Rectangular bodies

The first way we are going to implement detection is through the intersection of rectangles, which is also the simplest method.

We will use the bounding rectangle of the ScreenGameObject and check if it intersects with the bounding rectangle of the other ScreenGameObject.

The bounding rectangle changes each time we update the position of the sprite and, since we may be required to check with many other objects, it is best if we recalculate it after onUpdate. We are going to make a new method called onPostUpdate and do that inside it.

We have to add a new method to ScreenGameObject.

public void onPostUpdate(GameEngine gameEngine) {
  mBoundingRect.set(
    (int) mX,
    (int) mY,
    (int) mX + mWidth,
    (int) mY + mHeight);
}

If you need to override ...

Get Android Game Programming: A Developer’s Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.