Graphics Reference
In-Depth Information
directionVector.length() ) {
collisionResults[0].object
.material.transparent
= true;
collisionResults[0]
.object.material.opacity = 0.4;
}
}
In this piece of code, we simply check whether one of the vertices of our mov-
ing cube intersects with any of the cubes in the cubes array. If we detect a
collision, we change the opacity of the cube we collided with.
With these steps, we have a rudimentary solution to detect collisions. This approach
works great to detect collisions between flat objects but might miss detection with
small spike-like objects. You can enhance this solution by checking collisions against
more vertices. You can, for instance, add more vertices by increasing the
widthSegments , heightSegments , and depthSegments objects of the cube, or
you can calculate intermediate vertices yourself.
How it works…
To detect collisions in this approach, we shoot a ray using THREE.RayCaster from
the center of the cube that is moving to each of its vertices. If this ray intersects with
one of the other cubes from the cubes array in its path from the center to a vertex, it
means that one of the vertices is inside one of the other cubes. We interpret this as
a collision and can take appropriate action.
There's more…
This recipe is based on the great work done by Lee Stemkoski, who provided an ini-
tial implementation of this approach at http://stemkoski.github.io/Three.js/Collision-
Detection.html . Besides a ray-based approach to collision detection, there are, of
course, alternative approaches. A very common approach is to use the bounding
boxes of a mesh to detect whether two meshes touch. Three.js even provides a func-
tion for this in the THREE.Box3 object called isIntersectionBox . As using a ray
Search WWH ::




Custom Search