Javascript:检查两个div之间的碰撞

标签 javascript collision overlapping

有什么方法可以检查名称为“character”的 DIV 是否与名称为“ground”的 DIV 重叠?

我想用干净的 Javascript 来做到这一点,我知道 jQuery 更好,但这就是我不想要的。 我看到这个帖子:check collision between certain divs? ,但它不返回任何内容。

感谢您的帮助。

最佳答案

首先,我建议您检查一下 HTML5 canvas 元素,因为从它的声音来看,您想要制作一个游戏,而 canvas 非常棒为此;)

但是,要回答您的问题,您可以分别使用 document.createElement()getElementById() 创建或获取 div 元素,并通过以下方式获取其样式属性获取它们的 JS 设置值 (element.style) 或使用 getComputedStyle如果您希望在 CSS 中设置初始值。

确保,无论您如何获取这些 CSS 属性,它们都需要被解析为 JS 可以消化的内容。对于基于整数的位置,parseInt() 通常可以解决问题。

接下来,您进行数学计算。在本例中,您需要查看 Angular 色 div 的顶部加上其高度是否大于地面的顶部位置。如果是,则发生碰撞。

要将样式重新设置为 div,只需设置 style 属性即可。

这是一个示例(复制自 this fiddle ):

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),管理起来要困难得多。

关于Javascript:检查两个div之间的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17256719/

相关文章:

javascript - 为什么 var 在 with 语句中根据传递的对象是否具有同名属性而表现不同?

javascript - 在现代浏览器中覆盖全局变量

c++ - 如何在一个数组/容器中使用不同的对象?

jasper-reports - 生成的pdf文件中的文本换行问题

css - 如何防止div侧边栏重叠内容?

javascript - 具有 onclick 事件的重叠元素

javascript - 动态替换url参数

javascript - 在 JavaScript 中生成 UUID 时的冲突

java - java api中的UUID和碰撞

javascript - onclick 将数据传递给 javascript