Uncle Slug
Uncle Slug

Reputation: 913

How to find the position of a div while it is animating

For coding practice, I'm making a simple game where a gun, when clicked, will shoot a little red bullet at a moving target. In order for there to be any type of game, the changing positions of the bullet and target need to be compared so when an overlap of divs occurs (collision between bullet and target), it can be added to a conditional statement in order for points to score for instance.

The best way I can think to do this is by using a while loop when the gun is clicked to continually check the position of the two divs. However, when I run a test with console.log, the position of the bullet is always the same, despite the fact that the bullet is animating. I'm not sure what I'm doing wrong. I have the loop set up for testing purposes in the code below, so while (i<100) is only temporary.

JSBIN

JS

$(document).ready(function() {

  $('.allShips').animate({left: 400},5000,"linear");

  $('.gun').click(function() {

    $('.bullet').animate({top: '-10px'}, 1000,"linear", function(){
      $(this).animate({top: '385px'}, 0);
    });

  var i = 0;  
  var allShips = $('.ships');
  var overlap = true;
  var bullet = $('.bullet');
  while (i<100) {
    i++;
    var bulletPos = bullet.position();
  overlap = !(allShips.right < bullet.left || allShips.left > bullet.right || allShips.bottom < bullet.top || allShips.top > bullet.bottom);
    console.log(i+" Top: " + bulletPos.top);
   if (overlap === false) {
      $('.allShips').css('background-color', 'red');
   }
  }    
  }); 
});

Upvotes: 0

Views: 143

Answers (1)

Ash
Ash

Reputation: 1422

You may use :

 var myprop = getComputedStyle("idofanmdiv", null);

get property like :

myprop.left;myprop.top

Now you will get position while your div is animate :

 setInterval(function(){
  var myprop = getComputedStyle("idofanmdiv", null);
  elmtop = myprop.top;
  elmleft = myprop.left;
 },25);

If you want to detect collision between two div then : use collision detection with interval:

function collisions($div1, $div2) {
var x1 = $div1.offset().left;
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var w1 = $div1.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var w2 = $div2.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;

if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
  }

Like :

setInterval(function(){
 if(collisions($('.allShips'), $('.bullet'))){
   alert('shot Ok :)');
  }
},25);

Working JSBIN

Upvotes: 1

Related Questions