在THREE.JS中设置Sprite与Cylinder网格间的间距方法
实现Sprite与Cylinder的间距设置
你当前代码里把Cylinder作为Sprite的子对象,默认两者位置完全重合,只需要修改Cylinder的position属性就能设置两者的间距。
因为你已经通过geometry.rotateZ(-Math.PI * 0.5)把圆柱体绕Z轴旋转了90度,原本沿Y轴的圆柱体长度方向变成了X轴方向。根据需求调整位置参数即可:
- 若要让圆柱体沿自身长度方向和Sprite拉开距离,修改
position.x - 若要在垂直于圆柱体的方向调整间距,修改
position.y或position.z
比如要让圆柱体的一端刚好和Sprite边缘对齐(圆柱体高度为5,偏移2.5即可),可以在创建Cylinder后添加位置设置:
const cylinder = new THREE.Mesh( geometry, material ); // 添加这行代码设置间距,数值按需调整 cylinder.position.x = 2.5;
修改后的完整代码如下:
const THREE = this.context.three; const textureLoader = new THREE.TextureLoader(); const geometry = new THREE.CylinderGeometry( 0.09, 0.09, 5, 5 ); geometry.rotateZ(-Math.PI * 0.5); const material = new THREE.MeshBasicMaterial( {color: 0xFF00FF } ); const cylinder = new THREE.Mesh( geometry, material ); // 设置Cylinder与Sprite的间距,此处沿X轴偏移2.5 cylinder.position.x = 2.5; if (!this.inputs.sprite) { return; } if (!this.inputs.sprite.startsWith('/assets/')) { textureLoader.crossOrigin = 'Anonymous'; } let map; if (this.inputs.sprite.indexOf('.gif') !== -1) { map = new GifLoader().load(this.inputs.sprite); } else { map = textureLoader.load(this.inputs.sprite); } map.minFilter = THREE.LinearFilter; map.wrapS = map.wrapT = THREE.ClampToEdgeWrapping; this.material = new THREE.SpriteMaterial( { map, color: this.inputs.color, fog: false } ); this.material.alphaTest = 0.5; this.material.map.encoding = THREE.sRGBEncoding; this.sprite = new THREE.Sprite( this.material ); this.sprite.add(cylinder); this.onObjectReady(this.sprite, true);
你可以根据实际需求调整position的数值,正数或负数对应不同的偏移方向。
内容的提问来源于stack exchange,提问作者Y Z
相关产品推荐
相关产品推荐

