Within my project I have a character that automatically walks down the screen. I want to detect whenever the character hits a certain dungeon (each "dungeon" is a div
with some text inside).
Here is my code in a simplified format:
//call the function
console.log(isCollide(characterData[0][0], document.getElementsByClassName("Dungeon_Wrapper_Room")[a])));
var isCollide = function(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)));
return (
!((aTOP + 32) < (bTOP)) ||
(aTOP > (bTOP + 50)) ||
((aLEFT + 32) < aLEFT) ||
(aLEFT > (aLEFT + 50))
);
};
The character image was created dynamically (in the end I'll use a for loop to run through an array of characters, each with this detection).
var characterData = [
[document.createElement("img"), {/*Misc. Character Data Goes Here*/}]
];
characterData[0][0].src = "images/characters/default.png";
characterData[0][0].style.position = "relative";
characterData[0][0].style.left += ((50-32)/2)+"px";
characterData[0][0].style.top += (-(50-32+25))+"px";
characterData[0][0].id = "character0";
tavernBox.appendChild(characterData[0][0]);
My 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'>Boss
<!--Box character is being detected with-->
</div>
</div>
I've based my hit detection off the answer I found here: https://stackoverflow.com/a/7301852/7214959 but still am having no success.
I have absolutely no clue what is wrong with it. I've tried switching the <
around and other functions but still can't find anything. I've also tried going from relative
to absolute
positioning and still got nothing. The isCollide function needs to return true
or !false
to indicate it has collided but each section of the if statement always returns "false" and there is never a single "true".
JSFiddle (contains debugging for console and alert): https://jsfiddle.net/drfyvLng/
Solved: The selected answer solves the issue presented in the jsfiddle. Within my own code I had to turn the certain dungeon into absolute positioning and find its location use .offsetTOP
and .offsetLEFT
. Additionally I made the return formula detect when the character is inside the box rather than when it isn't.