我正在创建一个简单的游戏,您可以使用JQuery collision()
尝试使用JQuery collision()
来拍摄敌人的飞机,但它无法正常工作。我不知道这是if($('.blt').collision('.enmy')){
$('#enemy-plane').hide();
}
是如何运作的,但这是我试过的
{{1}}
和游戏http://codepen.io/akshay-7/pen/Ggjxwb
这个问题真有帮助,但我无法做到有人可以帮助我吗? How to detect if two divs touch with jquery?
答案 0 :(得分:2)
这应该做得很好:
$(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];
}