繁体   English   中英

移动div重力效果javascript / jquery

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM