【发布时间】:2017-08-08 00:07:55
【问题描述】:
在我的项目中,我有一个自动走下屏幕的角色。我想检测角色何时击中某个地牢(每个“地牢”都是div,里面有一些文字)。
这是我的简化格式代码:
//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))
);
};
字符图像是动态创建的(最后我将使用一个 for 循环来遍历一个字符数组,每个字符都有这个检测)。
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]);
我的 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>
我的命中检测基于我在这里找到的答案:https://stackoverflow.com/a/7301852/7214959,但仍然没有成功。
我完全不知道它有什么问题。我试过切换< 和其他功能,但仍然找不到任何东西。我也尝试过从relative 到absolute 定位,但仍然一无所获。 isCollide 函数需要返回true 或!false 以表明它已经发生碰撞,但是if 语句的每个部分总是返回“false”并且永远不会有一个“true”。
JSFiddle(包含控制台和警报调试):https://jsfiddle.net/drfyvLng/
已解决:所选答案解决了 jsfiddle 中提出的问题。在我自己的代码中,我必须将某个地牢转换为绝对定位并使用.offsetTOP 和.offsetLEFT 找到它的位置。此外,我让返回公式检测字符何时在框内而不是何时不在。
【问题讨论】:
-
ifs 条件中的表达式与返回的表达式~ !== !中的表达式不同。
标签: javascript collision-detection