有什么方法可以检查名称为“character”的 DIV 是否与名称为“ground”的 DIV 重叠?
我想用干净的 Javascript 来做到这一点,我知道 jQuery 更好,但这就是我不想要的。
我看到了这个帖子:检查某些div之间的碰撞?,但它不返回任何内容。
感谢帮助。
首先,我建议您查看 HTML5canvas
元素,从它的声音来看,你想要制作一个游戏,并且canvas
非常适合这个;)
但是,要回答您的问题,您可以使用以下命令创建或获取 div 元素document.createElement()
or getElementById()
分别通过获取它们的 JS 设置值来获取它们的样式属性 (element.style
)或使用获取计算样式如果您希望在 CSS 中设置初始值。
确保无论您如何获取这些 CSS 属性,都需要将它们解析为 JS 可以消化的内容。对于基于整数的头寸,parseInt()
通常可以达到目的。
接下来,您进行数学计算。在本例中,您需要查看角色 div 的顶部加上其高度是否大于地面的顶部位置。如果是的话,那就是碰撞了。
要将样式设置回 div,只需设置 style 属性即可。
这是一个例子(复制自这把小提琴):
var character = document.getElementById("character");
var ground = document.getElementById("ground");
//We could use getComputedStyle to get the style props,
//but I'm lazy
character.style.top = "10px";
character.style.height = "40px";
ground.style.top = "250px";
//For every 33ms (about 30fps)
setInterval(function(){
//Get the height and position of the player
var charTop = parseInt(character.style.top),
charHeight = parseInt(character.style.height);
//and the top of the ground
var groundTop = parseInt(ground.style.top);
//linear gravity? Why now?
charTop += 5;
//If the character's bottom is hitting the ground,
//Stop moving
if(charTop + charHeight > groundTop) {
charTop = groundTop - charHeight;
}
//Set the character's final position
character.style.top = charTop + "px";
},33);
#character {
position: absolute;
width: 40px;
height: 40px;
left: 50px;
background-color: #F00;
}
#ground {
position: absolute;
width: 300px;
height: 60px;
left: 0px;
background-color: #A66;
}
<div id="character"></div>
<div id="ground"></div>
另一件事:当元素使用不同的定位属性时,虽然有一些复杂的方法来获取元素位置(例如:玩家使用top
/left
坐标,地面使用的地方bottom
),管理起来比较困难。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)