Search code examples
javascripthtmlthree.jscollisiondetection

Collision Detection in FPS Game using three.js


I've been recently trying to fix my collision detection in my first person shooter three.js game but there are a few issues left I have not even the slightest idea on how to fix...

  • The camera can view inside walls
  • The collisions regularly push the player outside of the map

I have a jsfiddle available here: http://jsfiddle.net/sxv5fwL4/95/

And I have also received a little advice on the three.js subreddit under the post...

"Use of the "stemkoski" collision detection?"

I thank you in advance for your time, and thanks to /u/stovenn for his help in my reddit post.


Solution

  • This jsfiddle0 (see end of answer for updated versions) is a hacked version of the one cited. There was a problem with the Map which I have addressed by reading it as [u][v] and mapping Edit: (u-->z and v-->x). Now the layout of the map in the code is the same as the layout of the map in the simulation.

    I have used a very simple "(2D) Point in Bounding Box" collision test. It is based on testing whether the proposed new position of the player at each animation step locates inside the x-range and z-range of a wall cube. If it does then the proposed position is rejected and the (stored) previous position of the player is re-instated.

    Here is the core code:-

    if (   tile_x_min <= player_pos_x && player_pos_x <= tile_x_max
        && tile_z_min <= player_pos_z && player_pos_z <= tile_z_max )                              
    {
    collision_flag = true;
    player.velocity.x = 0;
    player.velocity.z = 0; 
    Message = "IN Wall Cell [" + x + "," + z +  "]" +
    "(x:" + tile_pos_x + ", z:" + tile_pos_z + ")";                                           
    }   
    

    I have used a little helper cube ("eddie") at the player position and moved the camera back a bit to make it visible. This helped a lot in troubleshooting glitches.

    Anyway give it a try if you like and let me know how it goes.

    Edit(1) jsfiddle1 Adds simple rotation of the player/camera. Use keys numpad_7 and numpad_9 to rotate left and right.

    Edit (2) jsfiddle2 responds to multiple keys being pressed at the same time. Also the eddie cube is hidden by using eddie.visible = false.

    Edit(3) jsfiddle3 Added independent camera rotation: up-centre-down (use Numpad keys 2,5,8). Player+camera horizontal rotation is by Numpad keys 4,6.