Shihan Khan
Shihan Khan

Reputation: 2188

jquery generate different id for each keypress event

Good day all, I'm trying to make a space shooting game using jquery and jquery-collision. I'm almost done finishing but one problem is, everytime I press spacebar to shoot it only creates same ID & class of projectile divs. So if the 1st projectile is being shot on a blank side & another one is being shot towards the enemy, after hit both of them disappear at the same time. Here are the codes:

function spawnBullet() { 
$("#content").append($("<div />")
.attr('id', 'projectile1')
.addClass("projectile")
.css({ "left" :  $('#fighter').offset().left + 25, 'top' : $('#fighter').offset().top - 20 })); 
}

function processBullet() {
$(".projectile").each(function() {
    var maxTop = $(this).offset().top;
    var breakable = $(".projectile").collision( "#boss" );
    //console.log(maxTop);
    $(this).css("top", maxTop - 3);
    if (maxTop <= 110 || breakable.length != 0) {
      $('#projectile1').remove();
      $("#score").html(++score);
    }

    if (breakable.length != 0) {
       breakable.remove();
       sound.play();
       spawnEnemy();
     }
});
}
setInterval(processBullet, 50);

function shoot() {
$(document).keydown(function(event) {
switch (event.keyCode) {
case 32:
    spawnBullet();
    break;
}
});
}

I want to create different id based divs for each spawnBullet() call. But I can't come up with any ideas. Need help desperately. Tnx.

Upvotes: 0

Views: 208

Answers (2)

James
James

Reputation: 22247

I'm not totally sure how some of these things work and this may be way off. You loop through every projectile using

$(".projectile").each(function() {...})

During each iteration you test if any of the bullets collided using

var breakable = $(".projectile").collision( "#boss" );

Would it not make sense to just test the bullet that is being iterated?

var breakable = $(this).collision( "#boss" );

and then

if (maxTop <= 110 || breakable.length != 0) {
  $(this).remove();

The benefit is that you don't need ids at all.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707406

You can create unique ids by just maintaining a global counter that you increment each time and then append that number onto the end of whatever root name you want to use.

For example:

var idCntr = 0;

function spawnBullet() { 
    $("#content").append($("<div />")
        .attr('id', 'projectile' + idCntr++)
        .addClass("projectile")
        .css({ "left" :  $('#fighter').offset().left + 25, 'top' : $('#fighter').offset().top - 20 })); 
}

If you don't want to create a new global variable or want to protect it from tampering, you can put it in a closure:

var spawnBullet = (function() {
    var idCntr = 0;

    return function () { 
        $("#content").append($("<div />")
            .attr('id', 'projectile' + idCntr++)
            .addClass("projectile")
            .css({ "left" :  $('#fighter').offset().left + 25, 'top' : $('#fighter').offset().top - 20 })); 
    }
})();

In other cases, the current time (in ms) serves as a unique enough id though you have to be careful if using this multiple times in a tight loop because you may get the same time value that way, but you won't get the same time value if you use it once per user event:

        .attr('id', 'projectile' + new Date().getTime())

If you're not saving this id somewhere, I might ask why you even need it?

Upvotes: 2

Related Questions