three.js - 当用户单击该面时绘制立方体的面
问题描述
我正在尝试做标题所说的。当用户点击立方体的一个面时,该面将改变颜色。
这是我的代码片段:
// 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:
}
}
}
此代码不完整。我的问题是这些:
- 我不知道这个策略是否正确并且有效
- 我不知道在不同情况下使用什么代码来绘制立方体的那一侧。
解决方案
首先,考虑将立方体的面分成绘制组。这个答案深入研究了如何做到这一点。
这个想法是立方体的所有面都将具有相同的颜色,但材料不同。这将允许您单独更改材质的颜色,因此您将单独更改立方体面的颜色。
当您收到来自 的回复时Raycaster
,请查找该faceIndex
属性。这将告诉您相交的面的索引。找到该索引所属的绘制组,然后您可以参考该组的材质索引,从而更改材质的颜色。
推荐阅读
- javascript - 单击按钮时仅展开一行
- c++ - vulkan - 计算队列族 - vkGetDeviceQueue - 访问冲突
- cmake - 即使正确设置了 BOOST_LIBRARYDIR,CMake Find Package Boost 也会失败
- python-3.x - 评估 CNN 准确性时 IPython Notebook 内核崩溃
- android-studio - Azure DevOps - Android - 在我的服务器上构建代理
- c# - 当我有多个路由属性时如何生成特定的操作 URL?
- r - R:如何按值或类型从列表中删除元素
- linux - 使用 perf 报告从特定的二进制文件中获取符号
- android - 如何修复“程序类型已存在:androidx.concurrent.futures.DirectExecutor”
- java - Mysql 8.0 的休眠配置