javascript - html/css/js 查找元素是否悬停在其他元素上

标签 javascript html css game-physics

我几个月前开始用 html/css/js 编写,我决定写一个没有任何库(比如 jQuery 或其他)的小 2d 游戏,它看起来像这样:

document.addEventListener("keydown",keyDown);
        
        function keyDown(e) {
            if(e.keyCode == 39) move(8, 0);
            if(e.keyCode == 37) move(-8, 0);
            if(e.keyCode == 40) move(0, -8);
            if(e.keyCode == 38) move(0, 8);
        }
        
        function move(X,Y) {
            var player=document.getElementById("player")
            var xBrk=Number(getComputedStyle(document.getElementById("brick")).getPropertyValue("left").replace('px',""));
            var yBrk=Number(getComputedStyle(document.getElementById("brick")).getPropertyValue("bottom").replace('px',""));
            var xWin=Number(getComputedStyle(document.getElementById("box")).getPropertyValue("width").replace('px',""))-Number(getComputedStyle(document.getElementById("player")).getPropertyValue("width").replace('px',""));
            var yWin=Number(getComputedStyle(document.getElementById("box")).getPropertyValue("height").replace('px',""))-Number(getComputedStyle(document.getElementById("player")).getPropertyValue("height").replace('px',""));
            var x=Number(getComputedStyle(player).getPropertyValue("left").replace('px',""))+X;
            var y=Number(getComputedStyle(player).getPropertyValue("bottom").replace('px',""))+Y;
            if ((x>=0&&x<=xWin)&&(x!==xBrk||y!==yBrk)) player.style.left=x + "px";
            if ((y>=0&&y<=yWin)&&(x!==xBrk||y!==yBrk)) player.style.bottom=y + "px";
        }
#box {
            position:absolute
            top:0px;
            left:0px;
            background-color:blue;
            width:512px;
            height:256px;
        }
        #player {
            position:absolute;
            bottom:32px;
            left:136px;
            background-color:red;
            width:8px;
            height:8px;
            z-index:2;
        }
        #world {
            position:relative;
            bottom:0px;
            left:0px;
            width:100%;
            height:100%;
            z-index:1;
        }
        #brick {
            position:absolute;
            bottom:0px;
            left:128px;
            background-color:black;
            width:32px;
            height:32px;
            z-index:1;
        }
<head>
</head>
<body>
    <div id="box">
        <div id="world">
            <div id="brick"/>
        </div>
        <div id="player"/>
    </div>
</body>

当玩家和积木的尺寸相同时,游戏运行良好,但是当我在 keyDown() 函数中将玩家的高度或宽度更改为小于积木尺寸的值(例如 8 和 - 8) 然后我移动到砖 block 上,玩家盖住砖 block 。几个小时后,我明白这是因为代码只识别了玩家和砖 block 的中心/位置,而不是整个方 block /碰撞框。我尝试进行过长的数学计算(100 多行!),但它仍然给了我一些错误(比如从底部而不是从顶部通过它的能力)。我的问题是: 我能找到一个元素是否悬停在另一个元素上吗(即使是 1 个像素)?如果是,我可以在多 block 砖上制作(具有不同的 ID)吗?

21/10 晚上 8 点更新
我回去工作,找到了一种通过为玩家和积木使用 Mx 和 Mn 变量来制作“物理”的方法。有了它们,我可以找到这两个元素,但我认为有一种更简单的方法可以做到这一点,但这仍然有一个错误:当我向右移动并撞到砖 block 时,我只能向左移动,当我向右移动时左边撞砖然后我只能往右走,和上下一样,我不知道怎么解决这个问题......

var brk = document.getElementById("brick");
var xBrk = Number(getComputedStyle(brk).getPropertyValue("left").replace('px', ""));
var xBrkMx = Number(getComputedStyle(brk).getPropertyValue("left").replace('px', "")) + Number(getComputedStyle(brk).getPropertyValue("width").replace('px', ""));
var yBrk = Number(getComputedStyle(brk).getPropertyValue("bottom").replace('px', ""));
var yBrkMx = Number(getComputedStyle(brk).getPropertyValue("bottom").replace('px', "")) + Number(getComputedStyle(brk).getPropertyValue("height").replace('px', ""));
var player = document.getElementById("player");
var xWin = Number(getComputedStyle(document.getElementById("box")).getPropertyValue("width").replace('px', "")) - Number(getComputedStyle(player).getPropertyValue("width").replace('px', ""));
var yWin = Number(getComputedStyle(document.getElementById("box")).getPropertyValue("height").replace('px', "")) - Number(getComputedStyle(player).getPropertyValue("height").replace('px', ""));
document.addEventListener("keydown", keyDown);

function keyDown(e) {
  var player = document.getElementById("player");
  if (e.keyCode == 39) move(8, 0);
  if (e.keyCode == 37) move(-8, 0);
  if (e.keyCode == 40) move(0, -8);
  if (e.keyCode == 38) move(0, 8);
}

function move(X, Y) {
  var x = Number(getComputedStyle(player).getPropertyValue("left").replace('px', "")) + X;
  var y = Number(getComputedStyle(player).getPropertyValue("bottom").replace('px', "")) + Y;
  var xMn = x - X - Number(getComputedStyle(player).getPropertyValue("width").replace('px', ""));
  var yMn = y - Y - Number(getComputedStyle(player).getPropertyValue("height").replace('px', ""));
  var xMx = x + Number(getComputedStyle(player).getPropertyValue("width").replace('px', "")) + Number(getComputedStyle(brk).getPropertyValue("width").replace('px', "")) - X;
  var yMx = y + Number(getComputedStyle(player).getPropertyValue("height").replace('px', "")) + Number(getComputedStyle(brk).getPropertyValue("height").replace('px', "")) - Y;
  if (xMx < xBrkMx || xMn > xBrk || yMx < yBrkMx || yMn > yBrk || ((xMx == xBrkMx && X == -8) || (yMx == yBrkMx && Y == -8) || (xMn == xBrk && X == 8) || (yMn == yBrk && Y == 8))) {
    if (x >= 0 && x <= xWin) player.style.left = x;
    if (y >= 0 && y <= yWin) player.style.bottom = y;
  }
}
#box {
  position: absolute;
  top: 0px;
  left: 0px;
  background-color: blue;
  width: 512;
  height: 256;
}

#player {
  position: absolute;
  bottom: 0px;
  left: 0px;
  background-color: red;
  width: 8;
  height: 8;
  z-index: 2;
}

#world {
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 1;
}

#brick {
  position: absolute;
  bottom: 0px;
  left: 128px;
  background-color: black;
  width: 32;
  height: 32;
  z-index: 1;
}
<head>
</head>
<body>
  <div id="box">
    <div id="world">
      <div id="brick" />
    </div>
    <div id="player" />
  </div>

最佳答案

我又开始思考这个问题了。改用这种方法怎么样?如果您这样做,以后添加更多对象会更容易。您将无法对所有积木等使用相同的 ID,因此您需要找到一种解决方法,但这允许您在 CSS 中设置宽度/高度并在 JS 中设置位置:

document.addEventListener("keydown",keyDown);

gameObjects = [];

const boxStyles = getComputedStyle(document.getElementById("box"))

// This does the same thing as your code was doing, just in two steps
// Putting a + before an string implicitly converts it to a Number with a positive value
const SCREEN_WIDTH = +boxStyles.getPropertyValue("width").replace('px',"");
const SCREEN_HEIGHT = +boxStyles.getPropertyValue("height").replace('px',"");

function createGameObject(id, x, y) {
    const retVal = {
        "id": id,
        "element": document.getElementById(id),
        "x": x,
        "y": y,
        "width": document.getElementById(id).offsetWidth,
        "height": document.getElementById(id).offsetHeight,
        "setScreenPosition": function(){this.element.style.left = this.x + "px"; this.element.style.top = this.y + "px";},
        "moveLeft": function() {this.x -= this.width; this.setScreenPosition();},
        "moveRight": function() {this.x += this.width; this.setScreenPosition();},
        "moveUp": function() {this.y -= this.height; this.setScreenPosition();},
        "moveDown": function() {this.y += this.height; this.setScreenPosition();},
        "setXY": function(x, y) {this.x = x; this.y = y; this.setScreenPosition();}
    }
    retVal.setScreenPosition();
    gameObjects.push(retVal);
    return retVal;
}

const myPlayer = createGameObject("player", 0, 0);
const myBrick = createGameObject("brick", 128, 32);
const myWall = createGameObject("wall", 256, 128);

function keyDown(e) {

    switch(e.keyCode) {
        case 37:
            moveLeft(myPlayer);
            break;
        case 38:
            moveUp(myPlayer);
            break;
        case 39:
            moveRight(myPlayer);
            break;
        case 40:
            moveDown(myPlayer);
            break;
    }
}

function moveLeft(gameObject) {
    let newX = gameObject.x - gameObject.width;

    if (newX < 0){
        console.log("Off the screen to the left.");
        return
    }
    // There are three lines here and they do the following:
    // Check if the gameObj[brick] will touch gameObject[Player] (x)
    // Check if the brick is in the way in the other dimension (y)
    // Check that the object we're comparing against isn't itself
    // I'm using filter to create an array of all objects in the way and then checking the length of that array.  An empty array means nothing in the way
    if (gameObjects.filter(gameObj=>gameObj.x <= newX && gameObj.x + gameObj.width >= gameObject.x && 
                                    gameObject.y >= gameObj.y && gameObject.y + gameObject.height <= gameObj.y + gameObj.height && 
                                    gameObj.id !== gameObject.id).length) {
        console.log("Hitting something on the left.");
        return;
    }
    gameObject.moveLeft();
}
function moveRight(gameObject) {
    let newX = gameObject.x + gameObject.width;

    if (newX >= SCREEN_WIDTH) {
        console.log("Off the screen to the right.");
        return;
    }
    if (gameObjects.filter(gameObj=>gameObj.x === newX && gameObject.y >= gameObj.y && 
                                    gameObject.y + gameObject.height <= gameObj.y + gameObj.height && 
                                    gameObj.id !== gameObject.id).length) {
        console.log("Hitting something on the right.")
        return;
    }
    gameObject.moveRight();
}
function moveUp(gameObject) {
    let newY = gameObject.y - gameObject.height;

    if (newY < 0) {
        console.log("Off the screen to the top.");
        return;
    }
    if (gameObjects.filter(gameObj=>gameObj.y <= newY && gameObj.y + gameObj.height >= gameObject.y &&
                                    gameObject.x >= gameObj.x && gameObject.x + gameObject.width <= gameObj.x + gameObj.width && 
                                    gameObj.id !== gameObject.id).length) {
        console.log("Hitting something above.");
        return;
    }
    gameObject.moveUp();
}
function moveDown(gameObject) {
    let newY = gameObject.y + gameObject.height;

    if (newY >= SCREEN_HEIGHT) {
        console.log("Off the screen to the bottom.");
        return;
    }
    if (gameObjects.filter(gameObj=>gameObj.y === newY && gameObject.x >= gameObj.x && 
                                    gameObject.x + gameObject.width <= gameObj.x + gameObj.width && 
                                    gameObj.id !== gameObject.id).length) {
        console.log("Hitting something below.");
        return;
    }
    gameObject.moveDown();
}
#box {
    position:absolute
    top:0px;
    left:0px;
    background-color:blue;
    width:512px;
    height:256px;
}
#player {
    position:absolute;
    background-color:red;
    width:8px;
    height:8px;
    z-index:2;
}
#world {
    position:relative;
    bottom:0px;
    left:0px;
    width:100%;
    height:100%;
    z-index:1;
}
#brick {
    position:absolute;
    background-color:black;
    width:16px;
    height:16px;
    z-index:1;
}

#wall {
    position:absolute;
    background-color:yellow;
    width:16px;
    height:48px;
    z-index:1;
}
<div id="box">
    <div id="world">
        <div id="brick"></div>
        <div id="wall"/></div>
        <div id="player"/></div>
    </div>
</div>

关于javascript - html/css/js 查找元素是否悬停在其他元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52916021/

相关文章:

javascript - 使用 javascript 的图像可见性

html - 如何在其他选择器上应用选择器样式?

jquery - 简单的图像变化

php - 将消失的默认文本 Your Name 添加到文本输入框

javascript - 仅使用 Vanilla 编码创建功能齐全的网站

javascript - 基本jQuery AJAX性能查询

javascript - 仅在所有 javascript 执行完毕后才显示页面

jquery - 切换不保持事件状态

jquery - 谷歌浏览器在 Windows 上插入框阴影错误,而不是在 Mac 上 : Better workaround?

javascript - 如何使活泼的 Accordion 看起来像一棵树