欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

使用javascript DOM的圓間碰撞檢測(cè)

我正在使用HTML、CSS和JS編寫(xiě)一個(gè)非畫(huà)布游戲;對(duì)于兩個(gè)圓之間的碰撞檢測(cè),我使用了兩個(gè)圓的斜邊和半徑。

對(duì)于x變量,我使用了左邊的CSS屬性,對(duì)于y變量,我使用了上面的CSS屬性(我使用了%而不是px,因?yàn)樗鼞?yīng)該是響應(yīng)性的)。不知怎么的,它不工作了,我似乎不知道問(wèn)題出在哪里。

food.style.top = random2 + "%";
food.style.left = random + "%";

// function for collision detection using pythagorean Theorem, if the distance between6 two circles is smaller than
// the sum of their radi than they are collidin
setInterval(function() {
  var playerX = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
  var foodX = parseInt(window.getComputedStyle(food).getPropertyValue("left"));
  var playerY = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
  var foodY = parseInt(window.getComputedStyle(food).getPropertyValue("top"));
  var playerRadius = parseInt(window.getComputedStyle(player).getPropertyValue("width"));
  var foodRadius = parseInt(window.getComputedStyle(food).getPropertyValue("width"));

  var adjacent = Math.abs(playerY - foodY);
  var opposite = Math.abs(playerX - foodX);

  var hypotenuse = Math.sqrt(Math.pow(adjacent, 2) + Math.pow(opposite, 2));
  var sumRadius = playerRadius / 2 + foodRadius / 2;

  if (hypotenuse < sumRadius) {
    food.style.top = random + "%";
    food.style.left = random + "%";
    score = score + 50;
  }
}, 10);

* {
  padding: 0;
  margin: 0;
}

body {
  background-color: antiquewhite;
}

#player {
  width: 10%;
  height: 20%;
  background-color: red;
  position: fixed;
  top: 35%;
  left: 35%;
  border-radius: 50%;
  z-index: 5;
}

#food {
  width: 5%;
  height: 10%;
  background-color: #ffd100;
  position: absolute;
  border-radius: 50%;
  top: 0%;
  left: 0%;
  z-index: -1;
}

<div id="player">
  <!--  <img src="png-clipart-smiley-desktop-happiness-face-smiley-miscellaneous-face-thumbnail.png" id="image"> -->
</div>
<div id="food"></div>

您可以使用getBoundingClientRect而不是computedStyle來(lái)查找DOM元素的位置。

我還建議使用transform而不是left和top來(lái)定位元素。可以用Math.hypot直接得出距離。

const circle1 = document.querySelector("#circle1").getBoundingClientRect()
const circle2 = document.querySelector("#circle2").getBoundingClientRect()

const dx = circle1.x - circle2.x;
const dy = circle1.y - circle2.y;
const distance = Math.hypot(dx,dy);

if(distance < 100) {
    console.log("circles are touching")
}

#circle1, #circle2 {
  width:100px;
  height:100px;
  position:absolute;
  border-radius:100%;
  background-color:blue;
}

#circle1 {
  transform:translate(10px, 20px);
}
#circle2 {
  transform:translate(30px, 50px);
}

<div id="circle1">

</div>
<div id="circle2">

</div>