JQuery碰撞不能正常工作 [英] JQuery collision not working properly

查看:110
本文介绍了JQuery碰撞不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个简单的游戏,你可以拍摄敌人飞机,我试图实现这个使用JQuery collision()但它不工作。我不知道这是 collision()如何工作,但这里是我尝试了

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

和游戏 http://codepen.io/akshay-7/pen/Ggjxwb

此问题真的有帮助,但我无法做到,有人可以帮助我吗? 如何检测两个div是否与jquery接触?

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?

推荐答案

这应该很好:

$(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];
}

这篇关于JQuery碰撞不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆