Game Development Reference
In-Depth Information
Listing 11-15. Excerpt from OverlapTester.java; Adding Sphere-Testing Methods
public static boolean
overlapSpheres(Sphere s1, Sphere s2) {
float
distance = s1.center.distSquared(s2.center);
float
radiusSum = s1.radius + s2.radius;
return
distance <= radiusSum * radiusSum;
}
public static boolean
pointInSphere(Sphere c, Vector3 p) {
return
c.center.distSquared(p) < c.radius * c.radius;
}
public static boolean
pointInSphere(Sphere c,
float
x,
float
y,
float
z) {
return
c.center.distSquared(x, y, z) < c.radius * c.radius;
}
That's again exactly the same code as in the case of circle overlap testing. We just use the
center of the spheres, which are a
Vector3
instances instead of a
Vector2
instances, as in the
case of a circle.
Note
Entire topics have been filled on the topic of 3D collision detection. If you want to dive deep into
that rather interesting world, we suggest the topic
Real-Time Collision Detection
, by Christer Ericson
(Morgan Kaufmann, 2005). It should be on the shelf of any self-respecting game developer!
GameObject3D and DynamicGameObject3D
Now that we have a nice bounding shape for our 3D objects, we can easily write the equivalent
of the
GameObject
and
DynamicGameObject
classes we used in 2D. We just replace any
Vector2
instance with a
Vector3
instance and use the
Sphere
class instead of the
Rectangle
class.
Listing 11-16 shows the
GameObject3D
class.
Listing 11-16. GameObject3D.java, Representing a Simple Object with a Position and Bounds
package
com.badlogic.androidgames.framework;
import
com.badlogic.androidgames.framework.math.Sphere;
import
com.badlogic.androidgames.framework.math.Vector3;
public class
GameObject3D {
public final
Vector3 position;
public final
Sphere bounds;
public
GameObject3D(
float
x,
float
y,
float
z,
float
radius) {
this
.position =
new
Vector3(x,y,z);
this
.bounds =
new
Sphere(x, y, z, radius);
}
}