Alinehx
Alinehx

Reputation: 13

how to use traverse in three.js to modify wireframe

I have several objects, when it was selected the check box would change the wireframe property to true or false ( run time) .

function toggleWireFrame(obj){
     var f = function(obj2)
     {
         if(obj2.hasOwnProperty("material")){
     obj2.material.wireframe=!obj2.material.wireframe;
     }          
  }
     obj.traverse(f);   
 }

Upvotes: 1

Views: 2465

Answers (2)

skeelogy
skeelogy

Reputation: 397

1) Your code should work, if you call toggleWireFrame on each of the meshes, one by one.

toggleWireFrame(meshA);
toggleWireFrame(meshB);

This would make sense if each of these meshes are made up of several meshes and you need to toggle all the sub-meshes too. You might get mesh hierarchies like that a lot if you import models from an OBJ file, for example.

2) Or did you want to call toggleWireFrame only once and have all your meshes' wireframe toggled?

If that's the case, you will have to call

toggleWireFrame(scene);

or even

toggleWireFrame(myObject3D);

where myObject3D is an Object3D instance which is the parent of all the meshes that you want to toggle wireframe status.

traverse() works by iterating through all children and grandchildren of the starting object. You need to make sure that all the objects that you want to toggle to wireframe is parented under this starting object, as shown in the examples above.

3) Another option is to use an array to store each material as they are created, and then iterate through this array to change the wireframe attribute when the user toggles the check box.

Upvotes: 1

Matthew Riches
Matthew Riches

Reputation: 2286

This is what I use on my projects, it just inverses the boolean since it will be true or false.

function wireframeToggle(i) {
    bool = i.material.wireframe;
    i.material.wireframe = !bool;
}

Working example (x for wireframe)

Upvotes: 0

Related Questions