大家好,我正在开发一个项目,Three.js
用户可以在该项目中hover
使用棋盘格化的面,每当网格相交且看不见球体时,应将每个网格推开,并在其区域外时回到其原始位置。我正在使用此示例和此示例作为参考,但是由于不知道如何使其工作而陷入困境Three.js
。
在我的代码中,我能够对hover
网格的每个面,将其设置为红色并在鼠标消失后恢复其原始颜色。但是我不能在这个职位上做类似的事情。这是我认为问题所在的代码部分:
if (intersects.length > 0) {
// if the closest object intersected is not the currently stored intersection object
if (intersects[0].object != INTERSECTED) {
// Restore previous intersection objects (if they exist) to their original color
if (INTERSECTED) {
INTERSECTED.face.color.setHex(INTERSECTED.currentHex);
}
// Intersected elements
INTERSECTED = intersects[0];
var intGeometry = INTERSECTED.object.geometry;
var intFace = INTERSECTED.face;
// Difference between intersected faces and geometry
INTERSECTED.currentHex = intFace.color.getHex();
intFace.color.setHex(0xc0392b);
intGeometry.colorsNeedUpdate = true;
// Identify the vertices of each face
var intVertices = intGeometry.vertices;
var v1 = intVertices[intFace.a],
v2 = intVertices[intFace.a],
v3 = intVertices[intFace.a];
// Calculate the centroid of the selected face
var intPosition = new THREE.Vector3();
intPosition.x = (v1.x + v2.x + v3.x) / 3;
intPosition.y = (v1.y + v2.y + v3.y) / 3;
intPosition.z = (v1.z + v2.z + v3.z) / 3;
console.log(intPosition);
}
}
通过console.log()
我可以看到正确识别了面孔及其位置,但是球体无法正确跟踪鼠标,因此我需要有关位置的帮助。这是带有完整代码的JSFiddle。
这是关于此主题的小测试:https : //jsfiddle.net/77xvepp7/
它仍无法正常工作,我将相机移得更远,以便可以看到主意。
基本思想是从曲面中选择一个顶点作为“基点”,就像在示例中所做的那样,它可以是曲面的中心,并保持该点为参考点,以将三角形中的所有其他点移动相同数量。如果您不保存原始值,则下一轮可能具有无效值,三角形将随机移动一点。
然后,计算鼠标到“基点”的距离,遍历所有顶点并将它们移至基点方向一定量。如果距离大于某个定义的量,请从顶点恢复原始值。
您可能尝试使用顶点着色器进行此操作,但是问题是,当鼠标位于曲面上方时,每个顶点都将朝相反的方向移动,而鼠标下方的三角形将缩放以填充空白。选择一个点作为“基点”可以解决此问题。
// Modify the geometry
var geometry = backgroundMesh.geometry;
for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
var face = geometry.faces[ i ];
if ( face instanceof THREE.Face3 ) {
var a = geometry.vertices[face.a];
var b = geometry.vertices[face.b];
var c = geometry.vertices[face.c];
var vList = [a,b,c];
// The trick is to save the original face positions
if(!a.origXSet) {
a.origX = a.x;
a.origY = a.y;
a.origZ = a.z;
a.origXSet = true;
}
var vect = a;
var dx = (vect.origX - pos.x),
dy = (vect.origY - pos.y),
dz = (vect.origZ - pos.z);
// distance to the mouse
var dist = Math.sqrt( dx*dx + dy*dy);
// magic constant, react if distance smaller than 4
if(dist < 4) {
vList.forEach(function(v) {
if(!v.origXSet) {
v.origX = v.x;
v.origY = v.y;
v.origZ = v.z;
v.origXSet = true;
}
var len = Math.sqrt(dx*dx + dy*dy + dz*dz);
if(len==0) return;
var ndx = dx / len,
ndy = dy / len,
ndz = dz / len;
v.x = v.origX + ndx * 2; // move 2 pixels
v.y = v.origY + ndy * 2;
v.z = v.origZ + ndz * 2;
});
} else {
// otherwise, reset coordinates
vList.forEach(function(v) {
if(v.origXSet) {
v.x = v.origX;
v.y = v.origY;
v.z = v.origZ;
}
});
}
geometry.verticesNeedUpdate = true;
geometry.normalsNeedUpdate = true;
}
}
主要问题是:鼠标指针在世界坐标中的位置未正确计算。目前,我没有精力去思考如何纠正该问题,但决定发布此答案,以便您可以继续进行下去。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句