萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 物理引擎入門:重力、碰撞、拖拽綜合運動效果實現

效果預覽

一個可拖拽、受重力影響、邊界彈性碰撞、摩擦力漸停的方塊運動模擬。在線演示

核心物理模型

概念代碼對應物理意義
位置obj.offsetLeft/Top元素相對定位父級的坐標
速度iSpeedX/Y每幀位移量(px/frame)
重力加速度iSpeedY += 3每幀 Y 速度增加 3px,模擬向下加速
彈性係數iSpeedY *= -0.8碰撞反向並損失 20% 能量
摩擦係數iSpeedX *= 0.8水平速度每碰撞衰減 20%
停止閾值Math.abs(iSpeedX) < 1速度極小時歸零,防止無限微動

完整代碼(ES6 重構版)

/**
 * Gravity-Collision-Drag-Move (GCDM)
 * 重力-碰撞-拖拽 運動控制器
 */
class GCDM {
    /**
     * @param {HTMLElement} obj - 目標元素 (需 position: absolute/fixed)
     * @param {number} initSpeedX - 初始水平速度
     * @param {number} initSpeedY - 初始垂直速度
     */
    constructor(obj, initSpeedX = 0, initSpeedY = 0) {
        if (!(obj instanceof HTMLElement)) {
            throw new Error('第一個參數必須是 HTMLElement');
        }
        this.obj = obj;
        this.speedX = initSpeedX;
        this.speedY = initSpeedY;
        this.timer = null;
        this.isDragging = false;
        this.lastPos = { x: 0, y: 0 };
        this._bindDragEvents();
    }

    // 核心運動循環
    _animate = () => {
        // 1. 應用重力
        this.speedY += 3; // g = 3px/frame²
        
        // 2. 計算新位置
        let left = this.obj.offsetLeft + this.speedX;
        let top  = this.obj.offsetTop  + this.speedY;
        
        // 3. 邊界檢測與碰撞響應
        const viewW = document.documentElement.clientWidth;
        const viewH = document.documentElement.clientHeight;
        const objW = this.obj.offsetWidth;
        const objH = this.obj.offsetHeight;
        
        // 底部碰撞
        if (top >= viewH - objH) {
            this.speedY *= -0.8;      // 反彈 + 能量損失
            this.speedX *= 0.8;       // 摩擦
            top = viewH - objH;       // 位置修正
        }
        // 頂部碰撞
        else if (top <= 0) {
            this.speedY *= -1;        // 完全彈性反彈
            this.speedX *= 0.8;
            top = 0;
        }
        
        // 右側碰撞
        if (left >= viewW - objW) {
            this.speedX *= -0.8;
            left = viewW - objW;
        }
        // 左側碰撞
        else if (left <= 0) {
            this.speedX *= -0.8;
            left = 0;
        }
        
        // 4. 微小速度歸零
        if (Math.abs(this.speedX) < 1) this.speedX = 0;
        
        // 5. 靜止判定:速度歸零且貼地
        if (this.speedX === 0 && this.speedY === 0 && top === viewH - objH) {
            this.stop();
            return;
        }
        
        // 6. 應用位置
        this.obj.style.left = left + 'px';
        this.obj.style.top = top + 'px';
    };

    // 拖拽交互綁定
    _bindDragEvents() {
        this.obj.onmousedown = (e) => {
            this.stop(); // 停止自動運動
            this.isDragging = true;
            this.lastPos = { x: e.clientX, y: e.clientY };
            
            // 提升層級防止被遮擋
            this.obj.style.zIndex = ++GCDM.zIndex;
            this.obj.classList.add('dragging');
            
            document.onmousemove = (e) => this._onDragMove(e);
            document.onmouseup = () => this._onDragEnd();
            e.preventDefault(); // 防止文字選中
        };
    }
    
    _onDragMove(e) {
        if (!this.isDragging) return;
        
        // 計算位移增量作為速度
        const dx = e.clientX - this.lastPos.x;
        const dy = e.clientY - this.lastPos.y;
        
        // 直接移動元素
        this.obj.style.left = (this.obj.offsetLeft + dx) + 'px';
        this.obj.style.top  = (this.obj.offsetTop  + dy) + 'px';
        
        // 速度 = 位移增量 (簡化模型,實際可乘以係數)
        this.speedX = dx;
        this.speedY = dy;
        
        this.lastPos = { x: e.clientX, y: e.clientY };
    }
    
    _onDragEnd() {
        this.isDragging = false;
        this.obj.classList.remove('dragging');
        document.onmousemove = null;
        document.onmouseup = null;
        
        // 釋放時保留速度,繼續物理運動
        this.start();
    }

    // 公共 API
    start() {
        if (this.timer) return;
        this.timer = requestAnimationFrame(this._animateLoop);
    }
    
    _animateLoop = () => {
        this._animate();
        if (this.timer) { // 未被 stop
            this.timer = requestAnimationFrame(this._animateLoop);
        }
    };
    
    stop() {
        cancelAnimationFrame(this.timer);
        this.timer = null;
    }
    
    destroy() {
        this.stop();
        this.obj.onmousedown = null;
        // 清理其他引用...
    }
}

// 靜態層級計數器
GCDM.zIndex = 1000;

// CSS 配合
/*
.dragging {
    cursor: grabbing !important;
    opacity: 0.8;
    box-shadow: 0 8px 24px rgba(0,0,0,0.2);
}
#box { position: absolute; width: 80px; height: 80px; background: #3498db; border-radius: 8px; }
*/

// 使用示例
document.addEventListener('DOMContentLoaded', () => {
    const box = document.getElementById('box');
    const gcdm = new GCDM(box, 100, 0); // 初始向右速度 100px/frame
    gcdm.start();
    
    // 可隨時控制
    // gcdm.stop();
    // gcdm.destroy();
});

關鍵改進點(對比原版)

  1. 使用 requestAnimationFrame 替代 setInterval:幀率自適應,瀏覽器優化,標籤頁隱藏自動暫停
  2. ES6 Class 封裝:消除全局變量,支持多實例獨立運行
  3. 事件綁定現代化:箭頭函數綁定 this,統一在 document 上監聽移動/釋放
  4. 物理參數可配置:重力、彈性、摩擦係數提取為常量,便於調整手感
  5. 狀態管理清晰:isDragging 互斥自動運動與手動拖拽
  6. 內存安全:提供 destroy() 清理引用

擴展方向

  • 多物體碰撞:引入空間劃分(QuadTree)檢測物體間碰撞
  • 旋轉物理:增加角速度、慣性矩、扭矩計算
  • 約束系統:彈簧、繩索、鉸鏈(Verlet Integration 更穩定)
  • 渲染分離:物理計算在 Worker,主線程只負責 transform: translate3d() 渲染
  • 集成 Matter.js / Box2D:生產級項目直接使用成熟物理引擎

總結

通過 位置 → 速度 → 加速度 → 碰撞響應 → 位置修正 的幀循環,配合拖拽時的速度采樣,即可實現逼真的 2D 物理運動。理解這套核心邏輯,是進階 Canvas/WebGL 動畫、游戲開發、交互可視化的基石。

copyright © 萬盛學電腦網 all rights reserved