DIV CSS 佈局教程網

JavaScript 重力彈跳拖拽效果:從物理參數到碰撞回彈
編輯:JavaScript綜合知識     

讓一個方塊在頁面裡自由落下、撞到邊界後彈開、還能用滑鼠抓起來甩出去——這個效果看起來複雜,拆開來其實只有「速度累加」「邊界檢測」「反向衰減」三件事。

調用方式

var GCDM = gcdMove(oDiv, 100, 0);
GCDM.startMove();   // 開始運動
GCDM.stopMove();    // 結束運動

參數說明:obj 是要動的元素(通常是某個 div);iSpeedX、iSpeedY 分別是水平(向右為正)與垂直(向下為正)的初速度,也可以傳 0 讓它自由落下。

完整實作

/**
 * 重力碰撞拖拽運動 - Gravity Crash Drag Move (gcdMove)
 */
function gcdMove(obj, iSpeedX, iSpeedY) {
  var _this = this;

  var iTimer;
  var iLastX = 0;
  var iLastY = 0;

  // 自動運動:每次都先清掉舊計時器,避免重複啟動
  var start = function () {
    clearInterval(iTimer);

    iTimer = setInterval(function () {
      iSpeedY += 3;   // 重力加速度

      var l = obj.offsetLeft + iSpeedX;
      var t = obj.offsetTop  + iSpeedY;

      // 上下邊界碰撞
      if (t >= document.documentElement.clientHeight - obj.offsetHeight) {
        iSpeedY *= -0.8;      // 反向並衰減,模擬能量損失
        iSpeedX *=  0.8;      // 落地摩擦
        t = document.documentElement.clientHeight - obj.offsetHeight;
      } else if (t <= 0) {
        iSpeedY *= -1;
        iSpeedX *=  0.8;
        t = 0;
      }

      // 左右邊界碰撞
      if (l >= document.documentElement.clientWidth - obj.offsetWidth) {
        iSpeedX *= -0.8;
        l = document.documentElement.clientWidth - obj.offsetWidth;
      } else if (l <= 0) {
        iSpeedX *= -0.8;
        l = 0;
      }

      // 速度歸零則停止水平移動
      if (Math.abs(iSpeedX) < 1) iSpeedX = 0;

      // 完全靜止於底部時收工
      if (iSpeedX == 0 && iSpeedY == 0
          && t == document.documentElement.clientHeight - obj.offsetHeight) {
        clearInterval(iTimer);
      }

      obj.style.left = l + 'px';
      obj.style.top  = t + 'px';
    }, 30);
  };

  _this.startMove = function () {
    obj.onmousedown = function (ev) {
      clearInterval(iTimer);      // 抓起來時先暫停物理計算

      var oEvent = ev || window.event;
      var disX = oEvent.clientX - obj.offsetLeft;   // 記下抓取點的偏移
      var disY = oEvent.clientY - obj.offsetTop;

      document.onmousemove = function (ev) {
        var oEvent = ev || window.event;
        var l = oEvent.clientX - disX;
        var t = oEvent.clientY - disY;

        obj.style.left = l + 'px';
        obj.style.top  = t + 'px';

        if (iLastX == 0) iLastX = l;
        if (iLastY == 0) iLastY = t;

        // 用位移差推算甩出的速度
        iSpeedX = l - iLastX;
        iSpeedY = t - iLastY;
        iLastX = l;
        iLastY = t;
      };
    };

    obj.onmouseup = function () {
      document.onmousedown = null;
      document.onmousemove = null;
      document.onmouseup   = null;
      start();                    // 放手後恢復物理運動
    };

    start();
  };

  _this.stopMove = function () {
    clearInterval(iTimer);
    obj.onmousedown     = null;
    document.onmousemove = null;
    obj.onmouseup       = null;
    iLastX = 0; iLastY = 0;
    iSpeedX = 0; iSpeedY = 0;
    disX = 0; disY = 0;
  };

  // 建構區:初速未傳則補 0
  (function () {
    if (!iSpeedX) iSpeedX = 0;
    if (!iSpeedY) iSpeedY = 0;
  })();
}

幾個物理細節值得說明

為什麼乘 -0.8 而不是 -1?完全彈性碰撞(乘 -1)會永遠彈跳不停。乘上小於 1 的係數模擬能量損失,跳幾下後自然停下來,視覺上才真實。

為什麼水平速度也要衰減?代表與地面/牆面的摩擦。少了這一步,方塊會在底部永遠左右滑動。

甩出手感的來源。拖曳時記錄「這一幀與上一幀的座標差」當作速度,放手瞬間沿用這個速度繼續跑——這就是「甩」的物理依據。位移差越大,甩得越遠。

可改進的地方

範例用 setInterval(…, 30) 驅動動畫。更好的做法是改用 requestAnimationFrame,它會與螢幕刷新率同步,在背景標籤頁自動暫停,也不會因為 30ms 與 16.7ms 不同步而產生撕裂感:

function loop() {
  // 更新位置
  rafId = requestAnimationFrame(loop);
}

另外範例中的 disX、disY 未宣告為區域變數,會變成全域污染;document.documentElement.clientHeight 也應改用更完整的視窗尺寸取得方式(例如 window.innerHeight)。這些都是可以在保持邏輯不變的前提下直接修掉的小問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved