# 初学three 添加sprite

### 1、模拟批量创建建筑

``````// 创建若干个建筑物

const buildCount = 50;

const group = new THREE.Group();

for (let i=0; i<buildCount; i++) {

const x = randWidth(20);

const y = randWidth(100);

const z = randWidth(10);

const boxGeometry = new THREE.BoxBufferGeometry(x, y ,z);

const positionX = 300 - randWidth(600);

const positionZ = 300 - randWidth(600);

boxGeometry.translate(positionX,  y / 2 ,positionZ);

const material = new THREE.MeshBasicMaterial( { color: 0x5588aa } );

const mesh = new THREE.Mesh(boxGeometry, material);

mesh.isBuild = true;

}

``````// 创建精灵函数，传入父对象

function createLableSprite_jcy(group, x, y, z) {

var spriteMaterial = new THREE.SpriteMaterial({

transparent: true, //开启透明(纹理图片png有透明信息)

});

// 创建精灵模型对象，不需要几何体geometry参数

var sprite = new THREE.Sprite(spriteMaterial);

sprite.scale.set(10, 10, 10); //精灵大小

sprite.position.set(x, y, z)

// 把精灵模型插入到模型对象的父对象下面

// 父对象group位置变化,网格模型及其对象的标签同样发生变化

group.position.set(group.position.x, group.position.y, group.position.z);

// 表示标签信息的精灵模型对象相对父对象设置一定的偏移

sprite.translateY(y+10);

return group;

}

## 代码示例

``````const geometry = new THREE.BoxGeometry( 1, 1, 1 );

const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );

const cubeA = new THREE.Mesh( geometry, material );

cubeA.position.set( 100, 100, 0 );

const cubeB = new THREE.Mesh( geometry, material );

cubeB.position.set( -100, -100, 0 );

//create a group and add the two cubes

//These cubes can now be rotated / scaled etc as a group

const group = new THREE.Group();

createLableSprite_jcy(mesh, positionX,  y / 2 ,positionZ);

### 3、移动的图标

``````const carGroup = new THREE.Group();

``````carGroup.rotation.y = - Math.PI / 2;

``````let spriteMaterial = new THREE.SpriteMaterial({

// 设置精灵纹理贴图

transparent: true, //开启透明(纹理图片png有透明信息)

});

// 创建精灵模型对象，不需要几何体geometry参数

const sprite = new THREE.Sprite(spriteMaterial);

sprite.scale.set(10, 10, 10); //精灵大小

// sprite.position.set(-1.6721884850946012, -1.368973127897772e-13, 360.53068686806284)

// 把精灵模型插入到模型对象的父对象下面

carGroup.position.set(-1.6721884850946012, -1.368973127897772e-13, 360.53068686806284);

sprite.translateY(carGroup.position.y + 20);

``````let progress = 0;

function moveCamera() {

if (progress <= 1 - 0.00004 * 20){

const point = curve.getPointAt(progress) //获取样条曲线指定点坐标，作为相机的位置

const pointBox = curve.getPointAt(progress + 0.00004 * 20) //获取样条曲线指定点坐标

if (carGroup) {

carGroup.position.set(pointBox.x, pointBox.y, pointBox.z);

carGroup.lookAt(point.x, point.y, point.z);

}

progress += 0.00004

} else {

progress = 0

}

}

### 参考链接：

Threejs使用精灵Sprite作为标签，鼠标悬浮精灵上时鼠变小手blog.csdn.net/baidu_29701…