I want to remove some cylinders that are in scene so i can put new ones in another position.
This is how I place the cylinders (this works just showing so you understand what I am trying to do).
for (i = 0; i < aantalLangs; i++) {
var geometry = new THREE.CylinderGeometry( (langsDiameter * scale), (langsDiameter * scale) , langsLengte * scale , 20 );
var material = new THREE.MeshBasicMaterial( {color: 0xffe26f} );
var cylinder = new THREE.Mesh( geometry, material );
scene.add( cylinder );
cylinder.position.set( 0 , 0 ,onderRandRooster);
onderRandRooster -= (langsMaas * scale);
cylinder.rotation.z = Math.PI / 2;
}
And I use this function to remove them.
function ClearMesh(){
scene.remove(scene.getObjectByName(cylinder));
scene.remove(scene.getObjectByName(cylinder2));
}
I want to use this button to remove the cylinders.
<button onclick="ClearMesh();">Clear mesh</button>
If you want to use Object3D.getObjectByName(), it's necessary to apply a string as a parameter. To be more precise, Object3D.name which you currently don't set in your application. Something like this should work:
// in your for loop
var cylinder = new THREE.Mesh( geometry, material );
cylinder.name = 'cylinder' + i;
// in your ClearMesh() function
scene.remove( scene.getObjectByName( 'cylinder1' ) );
Besides, consider to reuse your material and geometry when creating your cylinder meshes if they have the same properties. Just declare them outside of the for loop. Otherwise you should use the respective .dispose() methods in order to free internal resources of the engine when you remove a cylinder. Have a look at https://stackoverflow.com/a/40730686/5250847 for more details.
three.js R103
Related
I make a game where you can add objects to a world without using a grid. Now I want to make a footpath. When you click on "Create footpath", then you can add a point to on the world at the raycaster position. After you add a first point you can add a second point to the world. When these 2 objects where placed. A line/footpath is visible from the first point to the second one.
I can do this really simple with THREE.Line. See the code:
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vector3(x1,0,z1), new THREE.Vector3(x2,0,z2) );
lineGeometry.computeLineDistances();
var lineMaterial = new THREE.LineBasicMaterial( { color: 0xFF0000 } );
var line = new THREE.Line( lineGeometry, lineMaterial );
scene.add(line);
But I can't add a texture on a simple line. Now I want to do something the same with a Mesh. I have the position of the first point and the raycaster position of the second point. I also have the lenght between the two objects for the lenght of the footpath. But I don't know how I can get the rotation what is needed.
Note. I saw something about LookAt, is this maybe a good idea, how can I use this with a mesh?
Can anyone help me to get the correct rotation for the footpath object?
I use this code for the foodpath mesh:
var loader = new THREE.TextureLoader();
loader.load('images/floor.jpg', function ( texture ) {
var geometry = new THREE.BoxGeometry(10, 0, 2);
var material = new THREE.MeshBasicMaterial({ map: texture, overdraw: 0.5 });
var footpath = new THREE.Mesh(geometry, material);
footpath.position.copy(point2);
var direction = // What can I do here?
footpath.rotation.y = direction;
scene.add(footpath);
});
I want to get the correct rotation for direction.
[UPDATE]
The code of WestLangley helps a lot. But it works not in all directions. I used this code for the lenght:
var lenght = footpaths[i].position.z - point2.position.z;
What can I do that the lenght works in all directions?
You want to align a box between two 3D points. You can do that like so:
var geometry = new THREE.BoxGeometry( width, height, length ); // align length with z-axis
geometry.translate( 0, 0, length / 2 ); // so one end is at the origin
...
var footpath = new THREE.Mesh( geometry, material );
footpath.position.copy( point1 );
footpath.lookAt( point2 );
three.js r.84
I'm trying to create a clickable shape in Three from a bunch of points that are generated by mouse click.
This code is kind of working:
mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / player.width ) * 2 - 1;
mouse.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / player.height ) * 2 + 1
raycaster.setFromCamera( mouse, camera );
var objects = [];
objects.push(selectedHotspot);
var intersects = raycaster.intersectObjects( objects, true );
if ( intersects.length > 0 ) {
var point = new THREE.Mesh( new THREE.SphereGeometry(1, 1, 1), new THREE.MeshBasicMaterial( { color: 0x00ffff } ) );
point.position.copy(intersects[0].point);
scene.add(point);
points.push(intersects[0].point);
}
var geometry = new THREE.Geometry();
points.forEach( function( point ){
geometry.vertices.push( point );
});
geometry.vertices.push( points[0] );
geometry.faces.push( new THREE.Face3(0, 1, 2));
// material
var material = new THREE.MeshBasicMaterial( { color: 0xffffff } );
// line
var line = new THREE.Mesh( geometry, material );
scene.add( line );
hotspots.push( line );
The points get added, I can draw lines between them I just can't fill in the center so the mouse can detect it!
You can create a mesh from points using THREE.ConvexGeometry.
var mesh = new THREE.ConvexGeometry( vertices_array );
See, for example, https://threejs.org/examples/webgl_geometry_convex.html
This is just the convex hull of your points, but it should be sufficient for your use case.
You must include the three.js file examples/jsm/geometries/ConvexGeometry.js explicitly in your source code.
three.js r.147
There are different ways to create a mesh out of a point cloud - it all depends on what your specific needs are. I'll try to give you a high-level overview of a few approaches.
Perhaps a bounding box is enough? Calculate the bounding box of the point cloud and raycast against the BBox.
If the BBox happens to contains large volumes that have no points in them, then you may need a tighter-fitting mesh around these points. Given the ray being cast, project all points onto a plane normal to the ray, then construct the 2D convex hull of the points on this plane using the Gift wrapping algorithm. There are most likely existing libraries implementing this algorithm. Use the polygon constructed by this algorithm for the raycast test.
Using Three.js r75
I am trying to display cubes that change color depending on an integer value from green to red. I have tried multiple ways as I am stuck on this. I was unable to make cubeMat.material.color.setRGB work and creating a new Three.Color doesn't seem to work either. Please note I merge all the geometries at the end for one draw call. I am hoping this isn't the issue.
[UPDATE]
I am confirming the rgb values are set correctly with getStyle however they do not render correctly. All cube stacks should be different colors.
function colorData(percentage){
var rgbString = "",
r = parseInt(percentage * 25.5),
g = parseInt(((percentage * 25.5) - 255) * -1),
b = 0;
rgbString = "rgb("+r+","+g+",0)";
return rgbString;
}
...
var position = latLongToSphere(objectCoord[1], objectCoord[0], 300),
rgb = colorData(objectMag),
cubeColor = new THREE.Color(rgb),
cubeMat = new THREE.MeshBasicMaterial({color: cubeColor}),
cubeHeight = objectMag * 175,
cubeGeom = new THREE.BoxGeometry(3,3,cubeHeight,1,1,1),
cube = new THREE.Mesh(cubeGeom, cubeMat);
// set position of cube on globe, point to center, merge together for one draw call
cube.geometry.colorsNeedUpdate = true;
cube.position.set(position.x, position.y, position.z);
cube.lookAt(lookCenter);
cube.updateMatrix();
console.log(cube.material.color.getStyle());
geom.merge(cube.geometry, cube.matrix);
You are merging geometries so you can render with a single draw call and a single material, but you want each of the merged geometries to have a different color.
You can achieve that by defining vertexColors (or faceColor) in your geometry. Here is a pattern to follow:
// geometry
var geometry = new THREE.Geometry();
for ( var count = 0; count < 10; count ++ ) {
var geo = new THREE.BoxGeometry( 5, 5, 5 );
geo.translate( THREE.Math.randFloat( - 5, 5 ), THREE.Math.randFloat( - 5, 5 ), THREE.Math.randFloat( - 5, 5 ) );
var color = new THREE.Color().setHSL( Math.random(), 0.5, 0.5 );
for ( var i = 0; i < geo.faces.length; i ++ ) {
var face = geo.faces[ i ];
face.vertexColors.push( color, color, color ); // all the same in this case
//face.color.set( color ); // this works, too; use one or the other
}
geometry.merge( geo );
}
Then, when you specify the material for the merged geometry, set vertexColors like so:
// material
var material = new THREE.MeshPhongMaterial( {
color: 0xffffff,
vertexColors: THREE.VertexColors // or THREE.FaceColors, if defined
} );
Your geometry will be rendered with a single draw call. You can verify that by typing renderer.info into the console. renderer.info.render.calls should be 1.
three.js r.75
cubeMat.material.color.setRGB won't work because it's like you're calling the material twice (cubeMat and material), try this instead:
cube.material.color.setRGB( value, value, value );
Turns out if you merge the geometry the materials cant have different colors.
I had to set the face color of each cube before merging.
See
Changing material color on a merged mesh with three js
Three js materials of different colors are showing up as one color
I'm trying to add a line(s) between animated sprites, like in this example. I tryed different solutions. But I couldn't make a dynamic line and not even a static line between sprites that are animated. Is it possible to create a dymanic line between those sprites from that example. If yes, how can I do it?
This is the code I used:
for ( var i = 0; i < objects.length; i ++ ) {
var geometry = new THREE.Geometry();
geometry.vertices.push(objects.position);
var material = new THREE.LineBasicMaterial( {
color: 0x0000FF,
transparent: true,
opacity: 1
} );
var line = new THREE.Line( geometry, material, THREE.LinePieces );
scene.add( line );
}
On ...jsfiddle.net/LxpmN/40/ u can see what I'm try to achieve, but he used two meshes instead of sprites. I understand that I need to put line.geometry.verticesNeedUpdate = true;, but I can't even make a static line from objects, like in that previous example.
If you want to add a collection of line segments to your scene, create one THREE.Line instead of many. Use a pattern like this one:
var geometry = new THREE.Geometry();
for ( var i = 0; i < objects.length - 1; i ++ ) { // stop one short of end
geometry.vertices.push( objects[ i ].position );
geometry.vertices.push( objects[ i + 1 ].position );
}
var material = new THREE.LineBasicMaterial( { color: 0x0000FF } );
var line = new THREE.Line( geometry, material, THREE.LinePieces );
scene.add( line );
If you modify any of the object's positions, you will have to add the following line in the render loop:
line.geometry.verticesNeedUpdate = true;
three.js r.71
Hi folks,
I've got a question belongig surfaces in Three.js:
I got a bunch of Vec3 Points and want want to interpolate a surface through them. While searching, I stumbeled across beziers (three.js bezier - only as lines) and what looked more like I was searching : three.js Nurbs. I've tried to reconstruct the code, but the documentation was terrible (pages like this) and I didn't get how everything worked by reconstructing the code...
So here's the question:
Is there any easy way to get a shape out of my calculated points? (I would still be happy, if it's not interpolated).
Thank you guys!
Mat
Edit: What I want to acchieve is a surface plot. I stumbeled across http://acko.net/blog/making-mathbox/ but it's way too big for my needs...
After some try and error I found a solution: add a plane and than transform the single vertices.
// need to setup 'step', 'xStart', 'xEnd', 'yStart', 'yEnd'
// calc the variables
var width = Math.abs(-xStart+xEnd),
height = Math.abs(-yStart+yEnd);
var stepsX = width*step, stepsY = height*step;
var posX = (xStart+xEnd)/2;
var posZ = (yStart+yEnd)/2;
// add a plane and morph it to a function
var geometry = new THREE.PlaneGeometry( width, height, stepsX - 1, stepsY - 1 );
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
var size = stepsX * (stepsY),
data = new Float32Array( size );
var count = 0, scope = {};
mesh = new THREE.Mesh( geometry, new THREE.MeshNormalMaterial( {
side : THREE.DoubleSide,
transparent: true,
shading: THREE.SmoothShading,
opacity : _opacity }));
mesh.updateMatrixWorld();
// calc y value for every vertice
for ( var i = 0; i < size; i ++ ) {
// calculate the current values
// http://stackoverflow.com/questions/11495089/how-to-get-the-absolute-position-of-a-vertex-in-three-js
var vector = mesh.geometry.vertices[i].clone();
vector.applyMatrix4(
mesh.matrixWorld
);
// set them into the scope
scope.x = vector.x + posX;
scope.y = vector.z + posZ;
// calculate point and write it in a temp array
data[i] = math.eval(term, scope);
}
// push the new vertice data
for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) {
geometry.vertices[ i ].y = data[ i ];
}
// update the new normals
geometry.computeFaceNormals();
geometry.computeVertexNormals();
// add to scene
scene.add( mesh );
Only issue is that it is not working for non static functions like tan(x). This snippet is using math.js to calc the term.
Greetings Mat