threejs制作上升的小球
// 创建小球的函数
function createBall() {const radius = Math.random() * 0.2 + 0.1; // 随机半径 0.3-0.5const geometry = new THREE.SphereGeometry(radius, 32, 32);// 随机颜色const color = new THREE.Color(Math.random() * 0.5 + 0.5, // 0.5-1.0Math.random() * 0.5 + 0.5,Math.random() * 0.5 + 0.5);const material = new THREE.MeshBasicMaterial({color,// color: "#31f9c0",transparent: true, // 启用透明opacity: 0.9, // 透明度(0-1,0为完全透明)emissive: 0x31f9c0, // 自发光颜色(绿色)emissiveIntensity: 2, // 发光强度roughness: 0.1,metalness: 0.0,});for (let i = 0; i <= 10; i++) {const ball = new THREE.Mesh(geometry, material);// 随机位置在底部ball.position.x = (Math.random() - 0.5) * 120; // 这个是生成小球的长和宽ball.position.z = (Math.random() - 0.5) * 80;ball.position.y = -5 + radius;ball.userData = {speed: Math.random() * 0.05 + 0.03 // 0.03-0.08}scene.add(ball);balls.push(ball);}}
// 动画循环
const animateRender = () => {requestAnimationFrame(animateRender);// 随机生成新小球if (Math.random() < 0.05) { // 5%的几率生成新小球createBall();}// 更新所有小球位置for (let i = balls.length - 1; i >= 0; i--) {const ball = balls[i];ball.position.y += ball.userData.speed;// 如果小球超过一定高度,移除它if (ball.position.y > 40) {scene.remove(ball);balls.splice(i, 1);}}renderer.value.render(scene, camera.value)
};
这是案例的代码,想放进项目里是这样的效果。
思路:可以把这些balls放进一个group,然后可以改变group的位置,小球的位置会跟着改变