Reputation: 14368
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?
Upvotes: 1
Views: 224
Reputation: 5454
This should do it pretty well:
$(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];
}
Upvotes: 2