[英]Moving div gravity effect javascript/jquery
我正在使用javascript / jquery制作游戲,並且嘗試制作重力效果。 我有<div id="block"><img src="block/block1.png"/><div>
並且我希望它不斷向下移動,但我也希望它只是位於其他div的頂部而不是去通過他們。 到目前為止,我已經嘗試過:
var obj = $('#block');
function down()
{
obj.animate({top:'-=20'}, 1000, down);
}
down();
這個(小提琴)並不優雅,可以改進很多,但是可以用。 它使用一個非常簡單的碰撞模型和一個間隔計時器。 您將需要調整某些部分(希望您會進行改進)。
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);
})();
為防止出現負面評論和此類內容:是的,一旦文檔加載,就應調用此方法。 是的,此代碼很臟,不應在生產環境中使用。 正是它聲稱的那樣-一個有效的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.