tfe Homepage


Game creation: Adding moving collisions!

Here is the article 8 about my series of posts about the game creation.

If you missed it, check out the previous part.

So, now we have an "hexagone" structure, and a moving character, why not put them together? Let's add a simple player in the hexagone structure, but with collision detection to avoid him to pass throught the walls!

Internaly, the cells are inditified by their X/Y positions:

cells positions


To have better performance, the player mesh must be put in a simple structure with few vertices. The collision will be made between the obstacles (the walls) and those vertices.

The path collision algorithm is simple right now, but has to be improved:

  • The player ask to move to a custom position
  • A Raycast is traced between the player container + a small step value, and the obstacles (here: the walls meshes)
  • If the raycast send us a collision, disable the player movement

And, here is the part of the code:

               var originPoint = this.container.position.clone();
                var collision=false;

                for (var vertexIndex = 0; vertexIndex < this.container_mesh.geometry.vertices.length; vertexIndex++)
                    var localVertex = this.container_mesh.geometry.vertices[vertexIndex].clone();
                    var globalVertex = localVertex.applyMatrix4( this.container_mesh.matrix );
                    var directionVector = globalVertex.sub( this.container_mesh.position );

                    var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
                    var collisionResults = ray.intersectObjects( this.options.obstacles );
                    if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )

Here is the final result:


You can get: the source code or View the demo directly.