I am trying to find the intersect point between a ray from 'child' and a mesh (child2), using Raycaster:
var raycaster = new THREE.Raycaster();
var meshList = [];
meshList.push(child2);
for (var i = 0; i < child.geometry.vertices.length; i++) {
var diff = new THREE.Vector3();
diff.subVectors (child.geometry.vertices[i],child2.position);
raycaster.set(child.geometry.vertices[i],diff.normalize());
var intersects = raycaster.intersectObjects( meshList );
console.log(intersects[0].point);
}
But the above code is giving me error in the last line (console.log(intersects[0].distance)): "TypeError: undefined is not an object (evaluating 'intersects[0].point')".
How can I extract the intersect point between the ray and the 'child2' mesh?
Test to ensure there actually were results!
var intersects = raycaster.intersectObjects( meshList );
if (intersects.length) {
console.log(intersects[0].point);
} else {
console.log('ha, you missed me');
}
Related
I'm working on adapting the object loading example on the THREE.js example page to allow for the loaded objects to have their faces selected and colored. My general strategy has been to follow the steps outlined here.
However, since I am not using THREE.geometry objects, I am having trouble piecing together this strategy with the obj loader code.
I currently have ray intersection working so I know when I am clicking on the object, I am just having trouble coloring the faces. I know I need to apply: vertexColors: THREE.FaceColors to the obj material and thats where I'm stuck.
My current obj loading code is as follows:
var loader = new THREE.OBJLoader( manager );
loader.load( path, function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
var faceColorMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff, vertexColors: THREE.VertexColors } );
child.material = faceColorMaterial;
child.geometry.addAttribute( "color", new THREE.BufferAttribute( new Float32Array( 3 * 3 ), 3 ) );
child.geometry.dynamic = true;
}
} );
scene.add( object );
targetList.push(object);
}, onProgress, onError );
And my detection and coloring code:
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
vector.unproject( camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = ray.intersectObjects( targetList, true );
if ( intersects.length > 0 ) {
var colorArray = intersects[0].object.geometry.attributes.color.array;
var face = intersects[0].face;
colorArray[face.a] = 1;
colorArray[face.a + 1] = 0;
colorArray[face.a + 2] = 0;
colorArray[face.b] = 1;
colorArray[face.b + 1] = 0;
colorArray[face.b + 2] = 0;
colorArray[face.c] = 1;
colorArray[face.c + 1] = 0;
colorArray[face.c + 2] = 0;
intersects[0].object.geometry.attributes.color.needsUpdate = true;
}
When I run this, my object is black and when I click the faces, they do not change color.
How can I alter my code to allow for the changes to be colored when selected?
OBJLoader should be returning BufferGeometry objects, which don't use FaceColors. BufferGeometry can use VertexColors to assign colors to a face, but you need to ensure the colors attribute is applied to the BufferGeometry. If you do have a colors attribute, then you're in luck, because OBJLoader gives you unique vertices for each triangle.
When intersectObjects returns, the Face3 should have a, b, and c, which I believe should be indicies into the mesh.geometry.attributes.position.array, but they'll also be indices into the mesh.geometry.attributes.color.array array.
var colorArray = intersects[0].object.geometry.attributes.color.array,
face = intersects[0].face;
colorArray[face.a] = 1;
colorArray[face.a + 1] = 0;
colorArray[face.a + 2] = 0;
colorArray[face.b] = 1;
colorArray[face.b + 1] = 0;
colorArray[face.b + 2] = 0;
colorArray[face.c] = 1;
colorArray[face.c + 1] = 0;
colorArray[face.c + 2] = 0;
intersects[0].object.geometry.attributes.color.needsUpdate = true;
This should turn a particular face red. But I can't stress enough that this will only work if your geometry has a colors attribute, and your material is using THREE.VertexColors.
It seems like this should be easy, but I have spent nearly a week on this trying every possible combination of how to drag multiple items as a group in Three.js. It started out simple, I used this example https://jsfiddle.net/mz7Lv9dt/1/ to get the ball working. I thought I could just add some TextGeometry, which of course had some major API changes in the last couple releases rendering most examples obsolete.
After finally getting it to work as a single line, I wanted to add in wordwrap and move it as a group, but I can't seem to do so.
Here you can see it working just fine with the ball, but you can't drag the text https://jsfiddle.net/ajhalls/h05v48wd/
By swapping around three lines of code (location line 93-99), I can get it to where you can drag the individual lines around, which you can see here: https://jsfiddle.net/ajhalls/t0e2se3x/
function addText(text, fontSize, boundingWidth) {
var wrapArray;
wrapArray = text.wordwrap(10,2);
var loader = new THREE.FontLoader();
loader.load( 'https://cdn.coursesaver.com/three.js-74/examples/fonts/helvetiker_bold.typeface.js',
function ( font ) {
group = new THREE.Group();
group.name = "infoTag";
for (var i = 0; i < wrapArray.length; i++) {
var objectID=i;
var line = wrapArray[objectID];
var textGeo = new THREE.TextGeometry( line, {font: font,size: fontSize,height: 10,curveSegments: 12,bevelThickness: 0.02,bevelSize: 0.05,bevelEnabled: true});
textGeo.computeBoundingBox();
var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x );
var textMaterial = new THREE.MeshPhongMaterial( { color: 0xff0000, specular: 0xffffff } );
var mesh = new THREE.Mesh( textGeo, textMaterial );
mesh.position.x = centerOffset +200;
mesh.position.y = i*fontSize*-1+11;
mesh.position.z = 280;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.geometry.center();
mesh.lookAt(camera.position);
mesh.name = i;
group.add( mesh ); //this should work - comment out and swap for other two lines to see
scene.add(mesh); // this should work- comment out and swap for other two lines to see
//objects.push(mesh);//works on individual lines if you uncomment this
//scene.add(mesh); //works on individual lines if you uncomment this
}
objects.push( group ); // this should work- comment out and swap for other two lines to see
});
}
That "should" be working according to everything I had researched over the last week. I had one moment where it was "working" but because of the size of the group object, the pivot points were wrong, the setLength function didn't work, and it flipped the object away from the camera. All in all it was a mess.
I did try using 2d objects such as canvases and sprites, but for reasons detailed here Three.js TextGeometry Wordwrap - drag as group couldn't get it working.
Please, someone help me!
The issue ended up being with the group. Previously I was creating it, adding objects to it with a position.z which increased the size of the box around the group, then after doing that I moved the box to in front of the camera and did a group.lookAt which meant that when I was dragging it everything including pivot point and looking at it from the back was wrong. The right way was to create the group, position it, face the camera, then add the text.
function addText(text, fontSize, wrapWidth, tagColor, positionX, positionY, positionZ) {
var wrapArray;
wrapArray = text.wordwrap(wrapWidth,2);
var loader = new THREE.FontLoader();
loader.load( '/js/fonts/helvetiker_bold.typeface.js', function ( font ) {
group = new THREE.Group();
group.position.x=positionX;
group.position.y=positionY;
group.position.z=positionZ;
group.lookAt(camera.position);
group.tourType = "infoTag";
group.name = "infoTag-" + objects.length;
group.dataID=objects.length;
group.textData=text;
for (var i = 0; i < wrapArray.length; i++) {
var objectID=i;
var line = wrapArray[objectID];
var textGeo = new THREE.TextGeometry( line, {
font: font,
size: fontSize,
height: 1,
curveSegments: 12,
bevelThickness: 0.02,
bevelSize: 0.05,
bevelEnabled: true
});
textGeo.computeBoundingBox();
var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x );
var textMaterial = new THREE.MeshPhongMaterial( { color: tagColor, specular: 0xffffff } );
var mesh = new THREE.Mesh( textGeo, textMaterial );
mesh.dataID=objects.length;
mesh.position.x = 0;
mesh.position.y = (i*mesh.geometry.boundingBox.max.y*-1)*1.15;
mesh.position.z = 0;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.geometry.center();
//mesh.lookAt(camera.position);
mesh.name = "infoTag-mesh-" + objects.length;
group.add( mesh );
}
scene.add(group);
objects.push( group );
});
}
Of course there were some changes to be made in the mouse events to take into account that you want to move the parent of the object, which looks something like this:
function onDocumentMouseDown(event) {
event.preventDefault();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
if (intersects[0].object.parent.tourType == 'infoTag') {
var manipulatingInfoTag = true;
SELECTED = intersects[0].object.parent;
}else{
SELECTED = intersects[0].object;
}
var intersects = raycaster.intersectObject(plane);
if (intersects.length > 0) {
offset.copy(intersects[0].point).sub(plane.position);
}
container.style.cursor = 'move';
}
isUserInteracting = true;
onPointerDownPointerX = event.clientX; onPointerDownPointerY = event.clientY; onPointerDownLon = lon; onPointerDownLat = lat;
}
I'm using the ExplodeModifier to duplicate the vertices so I can have individual control over Face3 objects.
For my specific example, this alone looks visually poor, so I decided to add 3 extra faces (per existing face) so I can have a pyramid shape pointing inwards the geometry.
I managed to modify the ExplodeModifier and create the extra faces, however I get several errors:
THREE.DirectGeometry.fromGeometry(): Undefined vertexUv and THREE.BufferAttribute.copyVector3sArray(): vector is undefined
I understand that now I have 9 extra vertices per face, so I need according uv's, and since I don't need a texture but a solid color I don't mind having the wrong uvs... So, I also duplicated the uvs and avoid the first warning but I can't get rid of the copyVector2sArray...
pseudo code:
var geometry = new THREE.IcosahedronGeometry( 200, 1 );
var material = new THREE.MeshPhongMaterial( { shading: THREE.FlatShading } );
var explodeModifier = new THREE.ExplodeModifier();
explodeModifier.modify( geometry );
var mesh = new THREE.Mesh( geometry, material );
scene.addChild( mesh );
The Explode Modifier has this pseudo code:
var vertices = [];
var faces = [];
for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
(...)
var extraFace1 = new THREE.Face3().copy(face)
extraFace1.c = geometry.vertices[0]
var extraFace2 = new THREE.Face3().copy(face)
extraFace2.b = geometry.vertices[0]
var extraFace3 = new THREE.Face3().copy(face)
extraFace3.a = geometry.vertices[0]
faces.push( extraFace1 );
faces.push( extraFace2 );
faces.push( extraFace3 );
}
geometry.vertices = vertices;
geometry.faces = faces;
```
I added an example HERE. It works, but I want to avoid the console warnings...
As pointed out by #mrdoob I was assigning a THREE.Vector3 and not an index to the added THREE.Face3.
var extraFace1 = new THREE.Face3().copy(face)
extraFace1.a = geometry.faces.length * 3 - 1
var extraFace2 = new THREE.Face3().copy(face)
extraFace2.b = geometry.faces.length * 3 - 1
var extraFace3 = new THREE.Face3().copy(face)
extraFace3.c = geometry.faces.length * 3 - 1
jsfiddle updated
As quads faces are no longer supported in three.js. I am having trouble Raycast picking segments between 4 vertices points as a square as they are now made up of triangle faces.
So my picking returns triangle shape not square:
var faces = 10;
var myplane = new THREE.Mesh(
new THREE.PlaneGeometry(1000, 1000, faces, faces),
new THREE.MeshNormalMaterial({
color: 0x993333,
wireframe: false
}));
objects.push(myplane);
scene.add(myplane);
//raycast code
if ( intersects.length > 0 ) {
_controls.noRotate = true;
var face = intersects[0].face;
var temp = intersects[0].object;
var geo = temp.geometry;
geo.vertices[face.a].z -= 20;
geo.vertices[face.b].z -= 20;
geo.vertices[face.c].z -= 20;
//want other face verts below basically
geo.vertices[face.d].z -= 20;
geo.vertices[face.e].z -= 20;
geo.vertices[face.f].z -= 20;
geo.verticesNeedUpdate = true;
if(intersects[ 0 ].faceIndex % 2 == 0){
// geo.vertices[intersects[0].faceIndex + 1].z = 40;
// console.log("Even face Index: " + intersects[ 0 ].faceIndex);
}else{
// console.log("Odd face Index: " + intersects[ 0 ].faceIndex -1);
//geo.vertices[intersects[0].faceIndex - 1].z = 40, of course doest work
}
}
Below is a 2d example for a better vsual...
Currently I get the red out-come , but I'm wanting to pick like the green example:
try this code to get intersection faces
if ( intersects.length > 0 )
{
var faceIndex = intersects[0].faceIndex;
var obj = intersects[0].object;
var geom = obj.geometry;
var faces = obj.geometry.faces;
var facesIndices = ["a","b","c"];
facesIndices.forEach(function(indices){
geom.vertices[faces[faceIndex][indices]].setZ(-10);
});
if(faceIndex%2 == 0){
faceIndex = faceIndex+1;
}else{
faceIndex = faceIndex-1;
}
facesIndices.forEach(function(indices){
geom.vertices[faces[faceIndex][indices]].setZ(-10);
});
geom.verticesNeedUpdate = true;
}
In the general case, getting and changing the geometry of a raycast to mesh triangle intersection is just:
var face = intersects[0].face;
var obj = intersects[0].object;
var geom = obj.geometry;
var vertA = geom.vertices[face.a];
var vertB = geom.vertices[face.b];
var vertC = geom.vertices[face.c];
vertA.setY(100);
vertB.setY(110);
vertC.setY(105);
geom.verticesNeedUpdate = true;
No need to iterate through the faces array, or build a contrived face vertex array just to loop through it in the next step.
I'm moving a camera through a scene that contains an obj I've loaded as a mesh, and I want to detect if the camera has collided with any of the walls of my obj.
I've based my code off this threejs example: http://threejs.org/examples/misc_controls_pointerlock.html, and tried to apply your example here: http://stemkoski.github.io/Three.js/Collision-Detection.html - but I can't seem to get a collision.
My example is here
and the relevant javascript is here:
If anyone can point me in the right direction on how to detect a collision, I'd be grateful. Here's the relevant piece of code:
var objects = [];
var oLoader = new THREE.OBJLoader();
//oLoader.load('models/chair.obj', function(object, materials) {
oLoader.load('models/model-for-threejs.obj', function(object, materials) {
// var material = new THREE.MeshFaceMaterial(materials);
var material = new THREE.MeshLambertMaterial({ color: 0x000000 });
//var material = new THREE.MeshBasicMaterial({wireframe: true});
object.traverse( function(child) {
if (child instanceof THREE.Mesh) {
//objects.push(child); //MH - not sure if the object needs to be added here or not, but if I do, this really bogs down things down
}
});
object.position.x = 0;
object.position.y = 12;
object.position.z = 0;
scene.add(object);
objects.push(object);
});
}
var curPos = controls.getObject().position; //gives the position of my camera
raycaster.ray.origin.copy( curPos );
//raycaster.ray.origin.y -= 10;
raycaster.ray.origin.z +=10; //guessing here, but since I'm moving in 2d space (z / x), maybe I should be moving my ray ahead in z space?
var intersections = raycaster.intersectObjects( objects ); //
var isOnObject = intersections.length > 0;
if (isOnObject){ console.log('collide' }; //MH - nothing happening here
Raycaster's intersect object takes an Object3D with children, and has a flag for recursion.
https://github.com/mrdoob/three.js/blob/master/src/core/Raycaster.js#L33
So it should look like this:
var intersections = raycaster.intersectObjects( yourRootObject3D, true );