Game Development Reference
In-Depth Information
•
Rays
: Just like we used the
Raycaster
class earlier to detect clicked objects,
we can also use it to detect collision between multiple objects with the
intersectObjects()
method. To do this, we can cast rays in multiple
directions from the object that needs to check for collision, such as the player;
for example, we could cast a ray from the player's position toward each of
the player's vertices. If an intersection occurs at a distance smaller than the
distance from the player's position to the vertex, a collision has occurred.
There are several problems with this method. First, it's inefficient for large
numbers of vertices or dynamic objects. Second, objects can escape detection if
they are not exactly in the direction of a ray. Lastly, rays check for intersection
using an approximation of objects' shapes, so irregularly-shaped objects
can be incorrectly selected. However, this is the simplest general-purpose
approach that can work without additional libraries or knowledge about the
world's layout.
•
Intersection
: We can manually compare objects' geometries and positions
to see if they overlap. Since detecting collision between complex 3D shapes
is mathematically difficult, most games use simplified approximations
instead of the actual geometry to make calculations easier. Even so,
3D collision detection algorithms are complex and slow unless we use
very simple shapes such as boxes or spheres that don't do a great job of
approximating our objects. It's also computationally expensive without
some complex optimizations such as using a data structure called an
Octree
to make sure only nearby objects need to check for collision. If you
want to try implementing your own collision, Three.js includes an Octree
implementation in the
examples/js
folder.
•
Libraries
: Luckily, we don't have to do complex collision detection manually,
as there are several libraries that can take care of the complications for us.
They also handle collision response and associated physics. The leading
contenders are:
°
Ammo.js
is a large but complete library compiled to JavaScript from
C++. It is available at
https://github.com/kripken/ammo.js/
.
°
Cannon.js
is a smaller library written from scratch in JavaScript
and inspired in part by concepts from Three.js. It is available at
https://github.com/schteppe/cannon.js
.
°
Physi.js
is a bridge between Ammo or Cannon and Three.js that also
runs the physics simulation in a separate thread to avoid blocking the
rendering. It is available at
https://github.com/chandlerprall/
Physijs
.