【问题标题】:Painting the faces of a cube when user clicks on that face当用户单击该面时绘制立方体的面
【发布时间】:2020-08-14 21:42:48
【问题描述】:

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

这是我的代码 sn-p:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 2022-01-15
      • 2012-12-07
      相关资源
      最近更新 更多