【发布时间】:2020-11-23 01:29:16
【问题描述】:
我正在尝试在我的游戏(这是一款手机游戏)中检测 JavaScript 中的碰撞检测,但我想不出该怎么做!
在我的 JavaScript 中有一个 id 为“playercircle”的圆圈,我想知道如何将它与其他元素(硬币、敌人、前任)碰撞。
这是硬币的尝试之一。但首先检查我所有的代码:
if (playercircle.style.left == coin.style.left && playercircle.style.left == coin.style.left) {
score++;
}
这是我的代码:
var score = 0;
const coin = document.querySelector(".coin");
coin.style.top = Math.random()*130 + "px";
const enemy = document.querySelector(".enemy")
enemy.style.top = Math.random()*100 + "px";
let playercircle=document.querySelector(".playercircle");
function moveLeft() {
let left = parseInt(window.getComputedStyle(playercircle).getPropertyValue("left"));
left -= 10;
playercircle.style.left = left + "px";
}
function moveUp() {
let top = parseInt(window.getComputedStyle(playercircle).getPropertyValue("top"));
top -= 10;
playercircle.style.top = top + "px";
}
function moveRight() {
let left = parseInt(window.getComputedStyle(playercircle).getPropertyValue("left"));
left += 10;
playercircle.style.left = left + "px";
}
function moveDown() {
let top = parseInt(window.getComputedStyle(playercircle).getPropertyValue("top"));
top += 10;
playercircle.style.top = top + "px";
}
if (playercircle.style.left == coin.style.left && playercircle.style.top == coin.style.top) {
score = score + 1;
alert(score)
}
body {
padding: 0;
margin: 0;
}
#game {
width: 300px;
height: 350px;
background-color: green;
border: 1px solid black;
margin: auto;
overflow: hidden;
}
.playercircle {
height: 50px;
width: 50px;
background-color: darkblue;
border-radius: 50%;
position: relative;
top: 130px;
left: 200px;
overflow: hidden;
}
.coin {
width: 50px;
height: 50px;
background-color: gold;
border-radius: 50%;
position: relative;
left: 50px;
overflow: hidden;
}
.enemy {
width: 50px;
height: 50px;
background-color: red;
position: relative;
left: 50px;
animation: enemy 3s infinite linear;
}
@keyframes enemy {
0%{top: 230px;}
50%{top: -120px;}
100%{top: 230px;}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Circle Game</title>
</head>
<body>
<button id="btn-up"onclick="moveUp()">UP</button>
<button id="btn-down"onclick="moveDown()">DOWN</button>
<button id="btn-left"onclick="moveLeft()">LEFT</button>
<button id="btn-right"onclick="moveRight()">RIGHT</button>
<div id="game">
<div class="playercircle"></div>
<div class="coin"></div>
<div class="enemy"></div>
</div>
</body>
</html>
当您运行它而不是键盘控件时,它会使用按钮控件,因为它是SoloLearn 上的一个代码位,一个适用于 Android/IOS 手机(以及计算机)的代码工具。
【问题讨论】:
标签: javascript html css ios collision