daniel
daniel

Reputation: 35733

abort object3d.traverse in three.js

How can I abort the traverse when I traverse a three.js object?

scene.traverse(x => {
        if (x.userData) 
             // stop traversing here
});

return and break do not work

Upvotes: 1

Views: 1056

Answers (1)

TheJim01
TheJim01

Reputation: 8886

Object3D.traverse code (r134)

You would need to modify the traverse function to bail based on output from your callback function.

Something like this (untested):

// three.js/src/core/Object3D.js

    traverse( callback ) {

        let bailedOut = callback( this );

        if( !bailedOut ) {

            const children = this.children;

            for ( let i = 0, l = children.length; i < l && !bailedOut; i ++ ) {

                bailedOut = children[ i ].traverse( callback );

            }

        }

        return bailedOut;

    }

And then call it like:

function doTheThing( node ) {
    let bailOut = false;
    if( node.userData ) {
        bailOut = true;
    }
    else {
        // do the thing
    }
    return bailOut;
}

scene.traverse( doTheThing );

The processing basically continues until your callback returns true, at which point it triggers a cascade back up the traverse recursion chain until it exits the original call.

Upvotes: 2

Related Questions