Blog de tfe, Perl, Web et Libre...?

Threejs Ennemy vision detection

PubliƩ le 21/10/2016 dans threejs

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

If you missed it, check out the previous part.

Video presentation

Here is a youtube presentation of the state of the project right now:

Ennemy vision animation

The ennemy path animation is made up by a few vertices starting from the player position to the vision direction.

Threejs vision detection
Threejs vision detection

A collision is made between those vertices and the environment. The vertices are then moved to the collision point, if any.

Threejs vision detection
Threejs vision detection

The part of the code:


    // Loop on each vertices of the vision geometry
    for (var vertexIndex = 1; vertexIndex <; vertexIndex++)
        var localVertex =[vertexIndex].clone();
        var globalVertex = localVertex.applyMatrix4( );
        var directionVector = globalVertex.sub( );

        var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize(),0, this.vision_distance);
        var collisionResults = ray.intersectObjects(obstacles);

        // In each update frame, we start by restoring the vision vertices values[vertexIndex].x = this.vision_orig_vertices[vertexIndex].x;[vertexIndex].y = this.vision_orig_vertices[vertexIndex].y;[vertexIndex].z = this.vision_orig_vertices[vertexIndex].z;;

        // If the ennemy  vision has a collision with "something"
        if ( collisionResults.length > 0 && collisionResults[0].distance < this.vision_distance)
            // If the collision is with a wall, update the vertice position
                var distance = collisionResults[0].distance;
      [vertexIndex].x *= distance / this.vision_distance;
      [vertexIndex].y *= distance / this.vision_distance;
      [vertexIndex].z *= distance / this.vision_distance;
            // If the collision if with the player, 
    // If there is a collision with the player, the character should run do the player position

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