开发者

Is There An Efficient jQuery Hittest?

I am creating a simple game with HTML, CSS, and JavaScript (jQuery). There is main ship, where al开发者_JAVA技巧l of the particles (bullets) originate from. They are each just divs. Then, enemy divs are places randomly throughout the screen.

I am looking for an efficient way to test if each particle is hitting a particular enemy. I have something that starts to work out fine, but gets bogged down incredibly fast. I am new to js, so my code is pretty messy and probably inefficient in many other ways. Any suggestions would be greatly appreciated!

Here is my section that creates enemies and tests for hitting:

var createEnemy = function(){
    var xRandom = Math.floor(Math.random() * (containerW-50));
    var yRandom = Math.floor(Math.random() * (containerH-50));
    var newEnemy = $('<div class="enemy"></div>');
    $(newEnemy).css({'left':xRandom,'top':yRandom}).appendTo('#container').fadeTo(200, .7);

    var hitTest = setInterval(function(){
        var enemy = $(newEnemy);
        var particle = $('.particle');  

        var enemyT = enemy.offset().top;
        var enemyB = enemy.height()+enemyT;
        var enemyL = enemy.offset().left;
        var enemyR = enemy.width()+enemyL;

        var particleT = particle.offset().top;
        var particleB = particle.height();
        var particleL = particle.offset().left;
        var particleR = particle.width();

        if(particleT >= enemyT-particleB && particleT <= enemyB && particleL >= enemyL-particleR && particleL <= enemyR){
            enemy.hide();
            var removeEnemy = setTimeout(function(){
                newEnemy.remove();
                clearInterval(hitTest, 0);
            },500);
        }
    }, 20);
}

var enemyInt = setInterval(createEnemy, 1000);

Is getting something like this to run smoothly in a browser realistic? Does my code just need some changes? You will probably need more context so:

EDIT 1/12/2012: Game Link Removed // Not Relevant

NOTE: This works best in Chrome and Safari at the moment.

EDIT 3/22/2011: Changed enemy fadeOut() to hide() so that you can see exactly when an enemy disappears (it is sometimes delayed). The hitTest only seems to trigger when you click on the actual enemy, so if it passes through, it is not being triggered.Also, I forgot to clearInterval on hitTest. This seemed to boost performance dramatically, but still isn't quite there.


If you want the best performance, drop jQuery and use native JavaScript.

If that isn't an option, profile the slowest parts and use native DOM there, e.g.

var newEnemy = $('<div class="enemy"></div>');

...becomes...

var newEnemy = document.createElement('div');
newEnemy.className = 'enemy';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜