TfeServer

Blog de tfe, Web, Unix et Scripts...?

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:

    collision_with_player=false;

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

        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
        this.vision.geometry.vertices[vertexIndex].x = this.vision_orig_vertices[vertexIndex].x;
        this.vision.geometry.vertices[vertexIndex].y = this.vision_orig_vertices[vertexIndex].y;
        this.vision.geometry.vertices[vertexIndex].z = this.vision_orig_vertices[vertexIndex].z;
        this.vision.geometry.verticesNeedUpdate=true;

        // 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
            if(collisionResults[0].object.name=='walls')
            {
                var distance = collisionResults[0].distance;
                this.vision.geometry.vertices[vertexIndex].x *= distance / this.vision_distance;
                this.vision.geometry.vertices[vertexIndex].y *= distance / this.vision_distance;
                this.vision.geometry.vertices[vertexIndex].z *= distance / this.vision_distance;
            }
            // If the collision if with the player, 
            if(collisionResults[0].object.name=='p')
            {
                collision_with_player=true;
            }
        }
    }
    // If there is a collision with the player, the character should run do the player position
    if(collision_with_player)
    {
        this.run();
    }

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