threejs制作上升的小球

Three.js实现上升小球效果

// 创建小球的函数
function createBall() {
    const radius = Math.random() * 0.2 + 0.1; // 随机半径 0.3-0.5
    const geometry = new THREE.SphereGeometry(radius, 32, 32);

    // 随机颜色
    const color = new THREE.Color(
        Math.random() * 0.5 + 0.5, // 0.5-1.0
        Math.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的位置,小球的位置会跟着改变

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值