一個可拖拽、受重力影響、邊界彈性碰撞、摩擦力漸停的方塊運動模擬。在線演示
| 概念 | 代碼對應 | 物理意義 |
|---|---|---|
| 位置 | obj.offsetLeft/Top | 元素相對定位父級的坐標 |
| 速度 | iSpeedX/Y | 每幀位移量(px/frame) |
| 重力加速度 | iSpeedY += 3 | 每幀 Y 速度增加 3px,模擬向下加速 |
| 彈性係數 | iSpeedY *= -0.8 | 碰撞反向並損失 20% 能量 |
| 摩擦係數 | iSpeedX *= 0.8 | 水平速度每碰撞衰減 20% |
| 停止閾值 | Math.abs(iSpeedX) < 1 | 速度極小時歸零,防止無限微動 |
/**
* 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();
});
requestAnimationFrame 替代 setInterval:幀率自適應,瀏覽器優化,標籤頁隱藏自動暫停this,統一在 document 上監聽移動/釋放isDragging 互斥自動運動與手動拖拽destroy() 清理引用transform: translate3d() 渲染通過 位置 → 速度 → 加速度 → 碰撞響應 → 位置修正 的幀循環,配合拖拽時的速度采樣,即可實現逼真的 2D 物理運動。理解這套核心邏輯,是進階 Canvas/WebGL 動畫、游戲開發、交互可視化的基石。