Book Image

Mastering Android Game Development

By : Raul Portales
Book Image

Mastering Android Game Development

By: Raul Portales

Overview of this book

Table of Contents (18 chapters)
Mastering Android Game Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
API Levels for Android Versions
Index

Circular bodies


The next type of body we can use to detect collisions is a circle. For that we are going to consider the diameter of the circle to be the largest of the dimensions of the sprite. We have to add a member variable to ScreenGameObject named mRadius and this code to the constructor of the sprite:

mRadius = Math.max(mHeight, mWidth)/2;

Note that other elements that inherit from ScreenGameObject may want to initialize the radius in a different way.

The calculation of a circular collision is fairly simple: we just have to measure the distance between the centers of the two circles and check if it is smaller than the sum of the radius.

With circular bodies, the collision can occur outside the rectangle of the sprite

Because calculating square roots is a much more time consuming operation than a multiplication, we will use the square of the distance as defined by the Pythagorean theorem: distance2 = Δx2 + Δy2.

The code to check circular collisions is like this:

private boolean checkCircularCollision...