Ok. So, I’m trying to find out when 2 images collide in a game I made, but I’ve been receiving conflicting advice and I’m not exactly sure how to get any of the solutions to work (as all of them result in errors, and the collision results as null)
here are the two options I’ve been trying to solve (any solution works really, I’m just stumped and can’t seem to get it to work regardless of what I try).
// first option
function trackXY(){
for(let i=0; i<2; i++){
let playerrr = document.getElementById('moveAva');
let pikaTest = document.getElementById('pikaLocation' + i);
let playHeight = window.getComputedStyle(playerrr).getPropertyValue('height');
let playWidth = window.getComputedStyle(playerrr).getPropertyValue('width');
let playLeft = window.getComputedStyle(playerrr).getPropertyValue('left');
let playTop = window.getComputedStyle(playerrr).getPropertyValue('top');
let pokeHeight = window.getComputedStyle(pikaTest).getPropertyValue('height');
let pokeWidth = window.getComputedStyle(pikaTest).getPropertyValue('width');
let pokeLeft = window.getComputedStyle(pikaTest).getPropertyValue('left');
let pokeTop = window.getComputedStyle(pikaTest).getPropertyValue('top');
let xPlayer = parseInt(playLeft + .5*playWidth);
let yPlayer = parseInt(playTop + .5*playHeight);
let xEnemy = parseInt(pokeLeft + .5*pokeWidth);
let yEnemy = parseInt(pokeTop + .5*pokeHeight);
let rPlayer = .5*parseInt(playHeight);
let rEnemy = .5*parseInt(pokeHeight);
let dX = xEnemy - xPlayer;
let dY = yEnemy - yPlayer;
let distance = Math.sqrt((dX*dX)+(dY*dY))
if(distance <= (rEnemy+rPlayer)){
alert("collison!");
playHeight = parseInt(playHeight) + .5*parseInt(pokeHeight);
document.getElementById('pikaInvent').style.display = "block";
document.getElementById('pikaWon').style.display = "block";
}
}
}
//second option
function trackXY(){
for(let i=0; i<1; i++){
let playerrr = document.getElementById('moveAva');
let pikaTest = document.getElementById('pikaLocation' + i);
let xPlayer = parseInt(playerrr.style.left + .5*playerrr.style.width);
let yPlayer = parseInt(playerrr.style.top + .5*playerrr.style.height);
let xEnemy = parseInt(pikaTest.style.left + .5*pikaTest.style.width);
let yEnemy = parseInt(pikaTest.style.top + .5*pikaTest.style.height);
let rPlayer = .5*parseInt(playerrr.style.height);
let rEnemy = .5*parseInt(pikaTest.style.height);
let dX = xEnemy - xPlayer;
let dY = yEnemy - yPlayer;
let distance = Math.sqrt((dX*dX)+(dY*dY))
if(distance <= (rEnemy+rPlayer)){
alert("collison!" + enemy.id);
}
}
}
trackXY();
if anyone could help, I could really appreciate it. Or, if you have another solution for collision detection with 2 rectangular images. Thanks!