跳到正文

个人记录

hhhhh

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

文章信息

收录
2026年5月5日
更新
2026年5月5日
篇幅
约 21 分钟

版本

  1. v3当前
  2. v2
  3. v1

// ==UserScript== // @name 原生JS物理爆炸+吸附+引力控制 (终极版) // @namespace http://tampermonkey.net/ // @version 4.0 // @description 点击爆炸,长按吸附,按空格键切换引力方向(下/上/无) // @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: 350,

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

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

// --- 引力状态 ---
// 0: 向下 (正常), 1: 向上 (反重力), 2: 无重力 (失重)
let gravityMode = 0;
const GRAVITY_MODES = [
    { name: "向下 ↓", val: 1 },
    { name: "向上 ↑", val: -1 },
    { name: "失重 ○", val: 0 }
];

// --- 初始化 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;
        }

        // 上下边界 (根据引力方向决定哪个是"地面")
        // 如果重力向下 (val > 0),地面在底部
        // 如果重力向上 (val < 0),地面在顶部
        // 如果无重力 (val == 0),两边都是墙壁

        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 drawStatus() {
    ctx.fillStyle = 'white';
    ctx.font = '16px Arial';
    ctx.fillText(`引力: ${GRAVITY_MODES[gravityMode].name} (按空格切换)`, 20, 30);
}

// --- 动画循环 ---
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();
    }

    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') {
        // 循环切换模式: 0 -> 1 -> 2 -> 0
        gravityMode = (gravityMode + 1) % GRAVITY_MODES.length;

        // 切换时唤醒所有粒子,防止它们卡在错误的表面上
        particles.forEach(p => p.wakeUp());
    }
});

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

})();

原文