简体   繁体   中英

Moving div gravity effect javascript/jquery

I am making a game with javascript/jquery and I am trying to make a gravity effect. I have <div id="block"><img src="block/block1.png"/><div> and I want it to constantly move down but I also want it just to sit on top of other divs instead of going right through them. So far I have tried:

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

This (fiddle) is not elegant and can be improved a lot, but it works. It uses a very simple collision model and an interval timer. You will need to adapt some parts (and you will hopefully improve it).

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);
})();

To prevent negative comments and such stuff: Yes, you should call this once the document has been loaded. Yes, this code is dirty and should not be used in a production environment. It is just what it claims to be - a working example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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