Collision and overlap detection in JavaScript
I'm new to programming and especially to javascript, I'm trying to create a minigame: there are two circles, I can command a circle to make circle1 overlap circle2 and when this happens there is a collision or overlap that activates an action, but I don't know how to create this piece of code that detects collisions or overlaps and executes the action, I tried to do an if in a function that when the y position of circle1 is equal to that of y of circle2 there is a alert that says the game is over but it happens that as soon as I move the circle the warning appears and not when they overlap. How can I correct? What am I doing wrong?
var pixelTop = 10;
var pixelLeft = 260;
function spostaSu() {
pixelTop += -10;
document.getElementById("contenuto").style.top = pixelTop+"px";
if (document.getElementById("contenuto").top === document.getElementById("contenutod").top) {
alert("Game Over");
}
}
function spostaGiu() {
pixelTop += 10;
document.getElementById("contenuto").style.top = pixelTop+"px";
}
function spostaSinistra() {
pixelLeft += -10;
document.getElementById("contenuto").style.left = pixelLeft+"px";
}
function spostaDestra() {
pixelLeft += 10;
document.getElementById("contenuto").style.left = pixelLeft+"px";
}
body {
background-color: #222222;
}
#contenuto {
background-color: #aaaaaa;
width: 40px;
height: 40px;
position: relative;
border-radius: 50px;
left: 260px;
top: 10px;
}
#contenutod {
background-color: #dddddd;
width: 40px;
height: 40px;
position: relative;
top: 10px;
border-radius: 50px;
}
button {
width: 50px;
height: 50px;
font-size: 30px;
font-weight: bold;
margin: auto;
}
.button1 {
margin-top: 300px;
}
#buttonDiv {
text-align: center;
width: auto;
height: auto;
background-color: transparent;
}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
<script src="script.js"></script>
</head>
<body>
<div id="contenuto"></div>
<div id="contenutod"></div>
<div id="buttonDiv">
<button onclick="spostaSu()" class="button1">⇧</button>
<br>
<button onclick="spostaSinistra()">⇦</button>
<button onclick="spostaGiu()">⇩</button>
<button onclick="spostaDestra()">⇨</button>
</div>
</body>
</html>
Function with if:
function spostaSu() {
pixelTop += -10;
document.getElementById("contenuto").style.top = pixelTop+"px";
if (document.getElementById("contenuto").top === document.getElementById("contenutod").top) {
alert("Game Over");
}
}
Sorry for name of variables but i’m italian
from Recent Questions - Stack Overflow https://ift.tt/2KLLHQZ
https://ift.tt/eA8V8J
Comments
Post a Comment