简体   繁体   中英

JQuery collision not working properly

I am creating a simple game where you can shoot enemy planes i am trying to achieve this using JQuery collision() but it is not working. I don't know if this is how collision() works but here is what i have tried

if($('.blt').collision('.enmy')){
$('#enemy-plane').hide();
}

and the game http://codepen.io/akshay-7/pen/Ggjxwb

this question was really helpful but i was unable to do it can someone help me? How to detect if two divs touch with jquery?

This should do it pretty well:

DEMO

崩溃

$(function() {
  var $pln = $('#plane').data('hit', !!0);
      $('#HUD')[0].textContent = 'Collisions:  0';

  $(document).on('click', function(){

    var $div = $('<div class="blt" />')
      .appendTo($pln);

    setTimeout(function() {
      $div.fadeOut(100, function() {
        $div.remove();
      })
    }, 300);

  })

  .on('keydown', function(e) { 
    var animationProps;

    e.preventDefault();

    switch(e.which) {
      case 37:
        animationProps = { left: "-=10px" }
        break;      
      case 38:
        animationProps = { top: "-=45px" }
        break;
      case 39:
        animationProps = { left: "+=45px" }
        break;        
      case 40:
        animationProps = { top: "+=45px" }
        break;
    }

    $pln
      .animate(animationProps, { duration: 200, queue: false, complete: checkCollisions });
  });

  function checkCollisions(){
    var $enemy = $("#enemy")[0],
        $hud = $('#HUD'),
        pos1 = getPosition($enemy),
        pos2 = getPosition(this);

    var hMatch = posEqual(pos1[0], pos2[0]),
        vMatch = posEqual(pos1[1], pos2[1]),
        match = hMatch && vMatch;

    if (match) {
      var hit = $('#plane').data('hit');

      hit || $('#plane').data('hit', !hit);

      if (hit) return;

      $hud[0].textContent = 'Collisions: ' + 
        (+$hud[0].textContent.substr(11)+1);

    } else {
      $('#plane').data('hit', !!hit);
    }
  }
});

function getPosition(entity) {
  var $entity = $(entity);
  var position = $entity.position();
  var width = $entity.width();
  var height = $entity.height();
  return [
    [position.left, position.left + width], 
    [position.top, position.top + height] 
  ];
}

function posEqual(pos1, pos2) {
  var x1 = pos1[0] < pos2[0] ? pos1 : pos2,
      x2 = pos1[0] < pos2[0] ? pos2 : pos1;
  return x1[1] > x2[0] || x1[0] === x2[0];
}

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