2013-11-02 30 views
0

我正在用javascript/jquery製作遊戲,我正在嘗試使重力效果。我有<div id="block"><img src="block/block1.png"/><div>,我希望它不斷下降,但我也希望它只是坐在其他div的頂部,而不是通過它們。到目前爲止,我曾嘗試:
移動div重力效應javascript/jquery

var obj = $('#block'); 
function down() 
{ 
obj.animate({top:'-=20'}, 1000, down); 
} 
down(); 

回答

1

This (fiddle)不優雅,可以提高了很多,但它的作品。它使用非常簡單的碰撞模型和間隔計時器。你需要調整一些部分(你會希望改進它)。

HTML:

<div class="gravity" style="width: 90px; height: 15px; background-color: red; position: absolute; top: 10px; left: 20px;"></div> 
<div class="gravity" style="width: 90px; height: 25px; background-color: green; position: absolute; top: 60px; left: 30px;"></div> 
<div class="gravity" style="width: 90px; height: 25px; background-color: gray; position: absolute; top: 30px; right: 45px;"></div> 
<div class="obstacle" style="width: 230px; height: 40px; background-color: blue; position: absolute; top: 240px; right: 19px;"></div> 
<div class="obstacle" style="width: 180px; height: 40px; background-color: blue; position: absolute; top: 90px; left: 30px;"></div> 

的JavaScript:

(function() { 
    // All falling objects 
    var gravity = $('.gravity'), 
    // All static objects 
     obstacle = $('.obstacle'); 
    var all = gravity.add(obstacle); 
    setInterval(function() { 
     // Calculate positions of all falling objects 
     gravity.each(function() { 
      var e = this, 
       g = $(this), 
       ypos = g.offset().top, 
       xpos = g.offset().left, 
       h = g.height(), 
       w = g.width(); 
      // Check whether something is in our way 
      var conflicts = false; 
      all.each(function() { 
       if(this === e) return; 
       var a = $(this); 
       if(xpos < a.offset().left + a.width() && xpos + w > a.offset().left) { 
        if(ypos + h > a.offset().top && ypos + h < a.offset().top + a.height()) { 
         conflicts = true; 
        } 
       } 
      }); 
      if(!conflicts) { 
       // Move down (real gravitation would be v = a * t) 
       g.css('top', g.offset().top + 3); 
      } 
     }); 
    }, 50); 
})(); 

爲了防止負面評論和這樣的東西:是的,你應該再調用這個文件已加載。是的,這段代碼很髒,不應該在生產環境中使用。這正是它聲稱的 - 一個工作的例子。