【ThreeJs】能设置尺寸大小的THREE.Sprite

默认情况下Threejs的精灵材质要改变大小只能依靠设置scale而不能像其他几何体一样设置长宽。


## 源码 看精灵材质的源码里的构造函数
let _geometry;

//……
//其他代码
//……

class Sprite extends Object3D {
    constructor(material) {
        super();
        this.type = 'Sprite';
        if (_geometry === undefined) {
            _geometry = new BufferGeometry();
            const float32Array = new Float32Array([
                -0.5, -0.5, 0,
                0, 0, 0.5,
                -0.5, 0, 1,
                0, 0.5, 0.5,
                0, 1, 1,
                -0.5, 0.5, 0,
                0, 1
            ]);
            const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
            _geometry.setIndex([0, 1, 2, 0, 2, 3]);
            _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
            _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
        }
        this.geometry = _geometry;
        this.material = (material !== undefined) ? material : new SpriteMaterial();
        this.center = new Vector2(0.5, 0.5);
    }
}

可以发现精灵材质虽然没有厚度但是内部也是有一个geometry 。这个geometry 就是一个长宽均为1的方形。


## 解决方法 解决方法也很简单,创建一个子类继承自THREE.Sprite,然后在子类里面替换geometry就可以了
class SceneObjectIcon extends THREE.Sprite {
    constructor() {
        super();
        
        let textureLoader = new THREE.TextureLoader()
        let path = '贴图的位置'
        let map = textureLoader.load(path, () => {
            this.#onImgLoad(type, pObject)
        })
        
        this.material = new THREE.SpriteMaterial({map})
    }
    #onImgLoad() {
        //根据贴图尺寸更改精灵原始大小,替换THREE.Sprite默认几何体
        let height = this.material.map.source.data.height
        let width = this.material.map.source.data.width
		//图片经常很大,实际项目里要修改尺寸
		//……
		//修改尺寸的代码
		//……
		//生成新的几何体
        this.geometry = new THREE.PlaneBufferGeometry(width, height)
    }
}

你可能感兴趣的:(javascript,es6)