0

I am trying to do what the title says. When a user clicks on a face of the cube, that face will change colour.

This is my code snippet:

// create a cube
var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00 }); //0xF7F7F7 = gray
cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.userData.originalColor = 0xffff00;

function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
         
        var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
        vector.unproject( camera );
        raycaster.set( camera.position, vector.sub( camera.position ).normalize() );

        var intersects = raycaster.intersectObject( cube );
        if ( intersects.length > 0 )
        {
            var index = Math.floor( intersects[0].faceIndex / 2 );
            switch (index)
            {
                 case 0: 
                 case 1: 
                 case 2: 
                 case 3: 
                 case 4: 
                 case 5: 
            }

        }
}

This code is incomplete. My problems are these:

  1. I don't know if this strategy is correct and works
  2. I don't know what code to use inside the different cases, in order to paint that side of the cube.
user1584421
  • 3,499
  • 11
  • 46
  • 86

1 Answers1

0

First, consider breaking the cube's faces into draw groups. This answer delves into how to do that.

The idea is that all of the cube's faces will have the same color, but not the same material. This will allow you to change the material's colors individually, and as such you will individually change the color of the cube faces.

When you get a response back from the Raycaster, look for the faceIndex property. This will tell you the index of the face that was intersected. Find which draw group that index belongs to, and you can then reference that group's material index, and thus change the color of the material.

TheJim01
  • 8,411
  • 1
  • 30
  • 54