3D Tic-Tac-Toe with Ray Intersection via THREE.js

Wednesday, December 4, 2013 Posted by Josh Staples
I have wanted to create a 3D tic-tac-toe game for years but was always put out by my ham-fisted approach to determining a winner. When resolving an issue at work the other day I realized I could put together a cool demo using rays and the raycaster object of THREE.js. See the demo here:  3D Tic-Tac-Toe Demo

3D tic tac toe using rays
While click interactions with THREE.js are old-hat by now, I thought it would be interesting to use rays and intersections to determine the winner.

In short I've created 49 rays that are checked after each user cube selection.  In my demo, I also created THREE.js ArrowHelpers to demonstrate the ray placement.  Here is a Gist showing the ray creation:



After setting up all the rays, the last step was to loop through an array of the rays and inspect each ray's individual collisions. If every intersected object has been selected by a single user, a winner is declared and the game is over.    Please note that intersected objects are not Object3D meshes but rather the faces of each individual mesh. In other words, we aren't looking for 3 sequential user intersections but rather twice that number.

The code is pretty modular and wouldn't take much work to make this demo work for  a 4x4x4 or NxNxN tic-tac-toe grid.   Feel free to check out the code at Github.