跳到正文

休闲·娱乐

非常好玩的

fby_tomato约 25 分钟
原文
文章信息与版本

文章信息

收录
2026年5月5日
更新
2026年7月6日
篇幅
约 25 分钟

版本

  1. v5当前
  2. v4
  3. v3
  4. v2
更早的 1 个版本
  1. v1
代码
// ==UserScript==
// @name         原生JS物理全能特效 (终极版)
// @namespace    http://tampermonkey.net/
// @version      5.0
// @description  点击爆炸 | 长按吸附 | 空格切换引力 | B键冲击波
// @author       You
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // --- 配置参数 ---
    const CONFIG = {
        particleCount: 15,
        minSize: 8,
        maxSize: 16,
        baseGravity: 0.5,
        friction: 0.98,
        groundFriction: 0.8,
        bounce: 0.4,
        maxParticles: 400,

        // 吸附配置
        holdDelay: 200,
        suctionStrength: 1.5,
        suctionRange: 600,

        // 冲击波配置
        shockwaveForce: 30,      // 冲击波最大推力
        shockwaveRadius: 300,    // 冲击波有效半径
        shockwaveDecay: 0.9,     // 视觉波纹衰减速度

        colors: ['#FF5733', '#33FF57', '#3357FF', '#F333FF', '#FF33A8', '#33FFF5', '#F5FF33']
    };

    // --- 状态管理 ---
    let gravityMode = 0;
    const GRAVITY_MODES = [
        { name: "向下 ↓", val: 1 },
        { name: "向上 ↑", val: -1 },
        { name: "失重 ○", val: 0 }
    ];

    // 冲击波状态
    let shockwaves = []; // 存储当前存在的冲击波对象 {x, y, radius, maxRadius}

    // --- 初始化 Canvas ---
    const canvas = document.createElement('canvas');
    canvas.style.position = 'fixed';
    canvas.style.top = '0';
    canvas.style.left = '0';
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.pointerEvents = 'none';
    canvas.style.zIndex = '999999';
    document.body.appendChild(canvas);

    const ctx = canvas.getContext('2d');
    let width, height;

    function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        canvas.width = width;
        canvas.height = height;
    }
    window.addEventListener('resize', resize);
    resize();

    // --- 鼠标状态 ---
    const mouse = { x: 0, y: 0, isDown: false, downTime: 0 };

    // --- 粒子类 ---
    class Particle {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this.radius = Math.random() * (CONFIG.maxSize - CONFIG.minSize) + CONFIG.minSize;
            this.color = CONFIG.colors[Math.floor(Math.random() * CONFIG.colors.length)];

            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 10 + 5;
            this.vx = Math.cos(angle) * speed;
            this.vy = Math.sin(angle) * speed - 5;

            this.mass = this.radius;
            this.isStatic = false;
            this.sleepTimer = 0;
        }

        update() {
            if (this.isStatic) return;

            // 1. 应用动态引力
            const currentGravity = CONFIG.baseGravity * GRAVITY_MODES[gravityMode].val;
            this.vy += currentGravity;

            // 2. 阻力
            this.vx *= CONFIG.friction;
            this.vy *= CONFIG.friction;

            // 3. 更新位置
            this.x += this.vx;
            this.y += this.vy;

            // 4. 边界检测
            this.handleBoundaries(currentGravity);
        }

        handleBoundaries(currentGravity) {
            // 左右墙壁
            if (this.x - this.radius < 0) {
                this.x = this.radius;
                this.vx *= -CONFIG.bounce;
            } else if (this.x + this.radius > width) {
                this.x = width - this.radius;
                this.vx *= -CONFIG.bounce;
            }

            const isGravityDown = currentGravity > 0;
            const isGravityUp = currentGravity < 0;

            // 底部碰撞
            if (this.y + this.radius > height) {
                this.y = height - this.radius;
                this.vy *= -CONFIG.bounce;
                this.vx *= CONFIG.groundFriction;
                if (isGravityDown && Math.abs(this.vy) < 1 && Math.abs(this.vx) < 0.5) {
                    this.trySleep();
                } else if (!isGravityDown) {
                    this.wakeUp();
                }
            }

            // 顶部碰撞
            if (this.y - this.radius < 0) {
                this.y = this.radius;
                this.vy *= -CONFIG.bounce;
                this.vx *= CONFIG.groundFriction;
                if (isGravityUp && Math.abs(this.vy) < 1 && Math.abs(this.vx) < 0.5) {
                    this.trySleep();
                } else if (!isGravityUp) {
                    this.wakeUp();
                }
            }
        }

        trySleep() {
            this.sleepTimer++;
            if (this.sleepTimer > 10) {
                this.isStatic = true;
                this.vx = 0;
                this.vy = 0;
            }
        }

        wakeUp() {
            if (this.isStatic) {
                this.isStatic = false;
                this.sleepTimer = 0;
            }
        }

        draw() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.fillStyle = this.color;
            ctx.fill();
            ctx.strokeStyle = 'rgba(0,0,0,0.1)';
            ctx.stroke();
            ctx.closePath();
        }
    }

    let particles = [];

    // --- 核心物理:粒子间碰撞 ---
    function resolveCollisions() {
        for (let i = 0; i < particles.length; i++) {
            let p1 = particles[i];
            for (let j = i + 1; j < particles.length; j++) {
                let p2 = particles[j];
                if (p1.isStatic && p2.isStatic) continue;

                const dx = p2.x - p1.x;
                const dy = p2.y - p1.y;
                const distSq = dx * dx + dy * dy;
                const minDist = p1.radius + p2.radius;

                if (distSq < minDist * minDist && distSq > 0) {
                    const distance = Math.sqrt(distSq);
                    const nx = dx / distance;
                    const ny = dy / distance;
                    const overlap = minDist - distance;

                    p1.wakeUp();
                    p2.wakeUp();

                    let moveP1 = !p1.isStatic;
                    let moveP2 = !p2.isStatic;

                    if (moveP1 && moveP2) {
                        const moveX = nx * overlap * 0.5;
                        const moveY = ny * overlap * 0.5;
                        p1.x -= moveX;
                        p1.y -= moveY;
                        p2.x += moveX;
                        p2.y += moveY;
                    } else if (moveP1) {
                        p1.x -= nx * overlap;
                        p1.y -= ny * overlap;
                    } else if (moveP2) {
                        p2.x += nx * overlap;
                        p2.y += ny * overlap;
                    }

                    const dvx = p2.vx - p1.vx;
                    const dvy = p2.vy - p1.vy;
                    const velAlongNormal = dvx * nx + dvy * ny;

                    if (velAlongNormal > 0) continue;

                    let jVal = -(1 + CONFIG.bounce) * velAlongNormal;
                    jVal /= (1 / p1.mass + 1 / p2.mass);

                    const impulseX = jVal * nx;
                    const impulseY = jVal * ny;

                    if (!p1.isStatic) {
                        p1.vx -= impulseX / p1.mass;
                        p1.vy -= impulseY / p1.mass;
                    }
                    if (!p2.isStatic) {
                        p2.vx += impulseX / p2.mass;
                        p2.vy += impulseY / p2.mass;
                    }
                }
            }
        }
    }

    // --- 吸附逻辑 ---
    function applySuction() {
        if (!mouse.isDown) return;
        const now = Date.now();
        if (now - mouse.downTime < CONFIG.holdDelay) return;

        for (let p of particles) {
            const dx = mouse.x - p.x;
            const dy = mouse.y - p.y;
            const distSq = dx * dx + dy * dy;

            if (distSq < CONFIG.suctionRange * CONFIG.suctionRange && distSq > 100) {
                const dist = Math.sqrt(distSq);
                const nx = dx / dist;
                const ny = dy / dist;
                const forceMagnitude = CONFIG.suctionStrength * (1 - dist / CONFIG.suctionRange) * 2;

                p.wakeUp();
                p.vx += nx * forceMagnitude;
                p.vy += ny * forceMagnitude;
            }
        }

        // 绘制吸附指示器
        if (now - mouse.downTime > CONFIG.holdDelay) {
            ctx.beginPath();
            ctx.arc(mouse.x, mouse.y, 15, 0, Math.PI * 2);
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
            ctx.lineWidth = 2;
            ctx.stroke();
            ctx.closePath();
        }
    }

    // --- 冲击波逻辑 ---
    function triggerShockwave() {
        // 添加一个新的冲击波到数组
        shockwaves.push({
            x: mouse.x,
            y: mouse.y,
            radius: 10, // 初始半径
            maxRadius: CONFIG.shockwaveRadius,
            opacity: 1.0
        });

        // 对范围内的粒子施加物理力
        for (let p of particles) {
            const dx = p.x - mouse.x;
            const dy = p.y - mouse.y;
            const distSq = dx * dx + dy * dy;

            if (distSq < CONFIG.shockwaveRadius * CONFIG.shockwaveRadius) {
                const dist = Math.sqrt(distSq);
                if (dist < 10) continue; // 避免除以零或过大力

                // 归一化方向向量 (从中心向外)
                const nx = dx / dist;
                const ny = dy / dist;

                // 计算力度:距离越近力度越大
                // 使用平方反比或线性衰减,这里用线性衰减更可控
                const forceRatio = 1 - (dist / CONFIG.shockwaveRadius);
                const force = CONFIG.shockwaveForce * forceRatio;

                // 唤醒粒子并施加速度
                p.wakeUp();
                p.vx += nx * force;
                p.vy += ny * force;
            }
        }
    }

    function updateAndDrawShockwaves() {
        for (let i = shockwaves.length - 1; i >= 0; i--) {
            let sw = shockwaves[i];

            // 更新半径和透明度
            sw.radius += 15; // 扩散速度
            sw.opacity -= 0.05; // 消失速度

            // 绘制冲击波圆环
            if (sw.opacity > 0) {
                ctx.beginPath();
                ctx.arc(sw.x, sw.y, sw.radius, 0, Math.PI * 2);
                ctx.strokeStyle = `rgba(255, 255, 255, ${sw.opacity})`;
                ctx.lineWidth = 4;
                ctx.stroke();
                ctx.closePath();
            }

            // 如果完全消失,移除
            if (sw.opacity <= 0 || sw.radius > sw.maxRadius) {
                shockwaves.splice(i, 1);
            }
        }
    }

    // --- 显示状态 ---
    function drawStatus() {
        ctx.fillStyle = 'white';
        ctx.font = '14px Arial';
        ctx.shadowColor = 'black';
        ctx.shadowBlur = 4;
        ctx.fillText(`引力: ${GRAVITY_MODES[gravityMode].name} (空格切换) | B键: 冲击波`, 20, 30);
        ctx.shadowBlur = 0;
    }

    // --- 动画循环 ---
    function animate() {
        ctx.clearRect(0, 0, width, height);

        applySuction();

        // 更新粒子物理
        for (let p of particles) {
            p.update();
        }

        // 解决碰撞
        for (let k = 0; k < 2; k++) {
            resolveCollisions();
        }

        // 绘制粒子
        for (let p of particles) {
            p.draw();
        }

        // 更新并绘制冲击波
        updateAndDrawShockwaves();

        drawStatus();

        // 清理过多粒子
        if (particles.length > CONFIG.maxParticles) {
            particles.splice(0, particles.length - CONFIG.maxParticles);
        }

        requestAnimationFrame(animate);
    }

    // --- 事件监听 ---

    document.addEventListener('mousemove', (e) => {
        mouse.x = e.clientX;
        mouse.y = e.clientY;
    });

    document.addEventListener('mousedown', (e) => {
        if (e.button !== 0) return;
        mouse.isDown = true;
        mouse.downTime = Date.now();
        mouse.x = e.clientX;
        mouse.y = e.clientY;

        // 点击产生爆炸粒子
        for (let i = 0; i < CONFIG.particleCount; i++) {
            particles.push(new Particle(e.clientX, e.clientY));
        }
    });

    const stopSuction = () => { mouse.isDown = false; };
    document.addEventListener('mouseup', stopSuction);
    document.addEventListener('mouseleave', stopSuction);

    // 键盘监听
    document.addEventListener('keydown', (e) => {
        // 空格或 G 切换引力
        if (e.code === 'Space' || e.key === 'g' || e.key === 'G') {
            gravityMode = (gravityMode + 1) % GRAVITY_MODES.length;
            particles.forEach(p => p.wakeUp());
        }

        // B 键触发冲击波
        if (e.key === 'b' || e.key === 'B') {
            triggerShockwave();
        }
    });

    // --- 启动 ---
    animate();

})();
原文