JSFiddle - React, Tailwind, and code Playground
HTML
<div id="Town_Wrapper">
<div id="townBoxWrapper">
<div id="tavernBox">
<!-- Characters are appended here -->
</div>
</div>
</div>
<div id="Dungeon_Wrapper">
<div class='Dungeon_Wrapper_Room' style="background-color: yellow; min-height:50px;">Boss
<!--Box character is being detected with-->
</div>
</div>
JavaScript
var tavernBox = document.getElementById("tavernBox");
var characterData = [
[document.createElement("img"), {/*Misc. Character Data Goes Here*/}]
];
//random 32x32 image
//PLEASE NOTE, I was not able to find a 32x32 pixel image on line to import, thus this one is 400x400. Sorry :/
characterData[0][0].src = "http://i.imgur.com/cXlPewW.png";
characterData[0][0].style.position = "relative";
characterData[0][0].style.left += 20+"px";
characterData[0][0].style.top += 20+"px";
characterData[0][0].id = "character0";
tavernBox.appendChild(characterData[0][0]);
var moveCharacters = function() {
var characterElement = document.getElementById("character0");
var str = characterElement.style.top;
characterElement.style.top = (parseInt(str.slice(0, str.length-2)) + 1) + "px";
setTimeout(moveCharacters, 100);
//call the hit detection function
console.log(isCollide(characterData[0][0], document.getElementsByClassName("Dungeon_Wrapper_Room")[0]));
};
moveCharacters();
function isCollide(a, b) {
//Used to parse get the x/y pixel coordinates by removing the "px" at the end of the string.
var aTOPstr = a.style.top;
var aTOP = (parseInt(aTOPstr.slice(0, aTOPstr.length-2)));
var aLEFTstr = a.style.left;
var aLEFT = (parseInt(aLEFTstr.slice(0, aLEFTstr.length-2)));
var bTOPstr = b.style.top;
var bTOP = (parseInt(bTOPstr.slice(0, bTOPstr.length-2)));
var bLEFTstr = b.style.left;
var bLEFT = (parseInt(bLEFTstr.slice(0, bLEFTstr.length-2)));
console.log(((aTOP + 32) > (bTOP))+" "+(aTOP < (bTOP - 32))+" "+((aLEFT + 32) > bLEFT)+" "+(aLEFT < (bLEFT + 50)));
if((~((aTOP + 32) < (bTOP)) ||(aTOP > (bTOP + 50)) || ((aLEFT + 32) < aLEFT) || (aLEFT > (aLEFT + 50))) === true) {
alert("The hit detection worked!");
}
return (
!((aTOP + 32) < (bTOP)) ||
(aTOP > (bTOP + 50)) ||
((aLEFT + 32) < aLEFT) ||
(aLEFT > (aLEFT + 50))
);
};