So, I have a var named inimigo
that is declared in function of a setInterval()
but on another function named checkcolisions
I want to get the positions of the inimigo
so I can check the collision with him and bala where i can get the position of bala
by declaring the function after the animate as you can see. After many tries, the ckeckcolision
always says inimigo
is not defined". How can I get the position of inimigo
and check the collision with bala
's position? If you have better ways to check the collision between the two please let me know, I will really accept them. Thanks for your time.
$(document).ready(function() {
"use strict";
$(document).on('keydown', function(e) {
var kp = e.keyCode;
var carro = $("#carro");
var bala = $("#bala");
e.preventDefault();
if (kp === 37 && carro.position().left > -500) {
carro.css("left", (carro.position().left - 7) + "px");
}
if (kp === 39 && carro.position().left < 350) {
carro.css("left", (carro.position().left + 7) + "px");
}
if (kp === 32) {
bala.show();
bala.css('left', (carro.offset().left + 67) + "px");
bala.css('top', (carro.offset().top - 20) + "px");
bala.animate({
"top": "-=100px"
}, "fast", checkCollisions);
}
});
var counter2 = 0;
var j = setInterval(function() {
var inimigo = $(".inimigo").clone();
$('.jogo2').html(inimigo);
inimigo.css('left', (Math.floor(Math.random() * 200) + 550));
inimigo.css('top', "150px");
}, 2000);
function getPositions(disparo) {
var $disparo = $(disparo);
var pos = $disparo.position();
var width = $disparo.width();
var height = $disparo.height();
return [
[pos.left, pos.left + width],
[pos.top, pos.top + height]
];
}
function comparePositions(p1, p2) {
var x1 = p1[0] < p2[0] ? p1 : p2;
var x2 = p1[0] < p2[0] ? p2 : p1;
return x1[1] > x2[0] || x1[0] === x2[0] ? true : false;
}
function checkCollisions() {
var disparo = inimigo;
var pos = getPositions(disparo);
var pos2 = getPositions(this);
var horizontalMatch = comparePositions(pos[0], pos2[0]);
var verticalMatch = comparePositions(pos[1], pos2[1]);
var match = horizontalMatch && verticalMatch;
if (match) {
alert("score +1");
}
}
});