首页 > 解决方案 > 当用户单击该面时绘制立方体的面

问题描述

我正在尝试做标题所说的。当用户点击立方体的一个面时,该面将改变颜色。

这是我的代码片段:

// 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: 
            }

        }
}

此代码不完整。我的问题是这些:

  1. 我不知道这个策略是否正确并且有效
  2. 我不知道在不同情况下使用什么代码来绘制立方体的那一侧。

标签: three.js

解决方案


首先,考虑将立方体的面分成绘制组。这个答案深入研究了如何做到这一点。

这个想法是立方体的所有面都将具有相同的颜色,但材料不同。这将允许您单独更改材质的颜色,因此您将单独更改立方体面的颜色。

当您收到来自 的回复时Raycaster,请查找该faceIndex属性。这将告诉您相交的面的索引。找到该索引所属的绘制组,然后您可以参考该组的材质索引,从而更改材质的颜色。


推荐阅读