Three.js: change the pivot point of a sprite

后端 未结 3 1161
南旧
南旧 2021-01-06 07:25

I\'ve created a 3D map and I\'m labelling points on this map through Sprites. This in itself works fine, except for the positioning of the sprite labels.

Because I\'

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 07:56

    This is very much a hack, but if you will only use sprites in this way, and could tolerate a global change to how sprites were rendered, you could change the following line in the compiled three.js script:

    Find (ctrl+F) THREE.SpritePlugin = function, and you'll see:

    this.init = function ( renderer ) {
    
        _gl = renderer.context;
        _renderer = renderer;
    
        vertices = new Float32Array( [
            - 0.5, - 0.5, 0, 0, 
              0.5, - 0.5, 1, 0,
              0.5,   0.5, 1, 1,
            - 0.5,   0.5, 0, 1
        ] );
    

    I changed the definition of the array to the following:

        var vertices = new Float32Array( [
            - 0.5, - 0.0,  0, 0,
              0.5, - 0.0,  1, 0,
              0.5,   1.0,  1, 1,
            - 0.5,   1.0,  0, 1 
        ] );
    

    And now all my sprites render with the rotation origin at the bottom.

    If you use the minified version, search for THREE.SpritePlugin=function and move the cursor right until you find the Float32Array defined, and make the same changes there.

    Note: this changes how things render only when using WebGL. For the canvas renderer you'll have to play a function called renderSprite() in the THREE.CanvasRenderer. I suspect playing with these lines will do it:

    var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
    _elemBox.min.set( v1.x - dist, v1.y - dist );
    _elemBox.max.set( v1.x + dist, v1.y + dist );
    

    This function will also be a lot more difficult to find in the minified version, since renderSprite() is not an outward facing function, it'll likely be renamed to something obscure and small.

    Note 2: I did try making these modifications with "polyfills" (or rather, redefining the SpritePlugin after Three is defined), but it caused major problems with things not being properly defined for some reason. Scoping is also an issue with the "polyfill" method.

    Note 3: My version of three.js is r69. So there may be differences above.

提交回复
热议问题