I want to activate a collision detection between the green and red div, simple, just square collision. I need it for a game like the dinosaur of google, I'm designing for a class proyect. I putted the var of the size form macaco and obstaculo in comment, beacuse something is not working in it, if i leave it normal, the jump function does not work.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inicio esqueleto</title>
<link rel="stylesheet" type="text/css" href="estilo.css">
</head>
<body>
<div onclick="saltar()" id="macaco" class="macaco"></div>
<div id="obstaculo"></div>
<script type="text/javascript">
var macaco = document.getElementById("macaco");
var obstaculo = document.getElementById("obstaculo");
function saltar(){
macaco.classList.add("play");
setTimeout(function(){
macaco.classList.remove("play");
},1000);
}
// var macaco = {x: 40, y: 70, width: 40, height: 70};
// var obstaculo = {x: 40, y: 50, width: 40, height: 50};
function collision(macaco, obstaculo){
if (macaco.x < obstaculo.x + obstaculo.width &&
macaco.x + macaco.width > obstaculo.x &&
macaco.y < obstaculo.y + obstaculo.height &&
macaco.y + macaco.height > obstaculo.y
) {
alert("It worked!")
// Colision detectada
} return true
}
</script>
</body>
</html>
#macaco {
background-color: green;
height: 70px;
width: 40px;
transform: translateX(15vw);
position: absolute;
bottom: 22px;
position: absolute;
}
#obstaculo {
background-color: red;
height: 50px;
width: 40px;
transform: translateX(50vw);
position: absolute;
bottom: 22px;
position: absolute;
animation: linear obstaculo 2s;
}
.play {
animation: linear saltar 1s;
}
@keyframes saltar {
0% {transform: translatey(0px) translateX(15vw)}
50% {transform: translatey(-120px) translateX(15vw)}
100% {transform: translatey(0px) translateX(15vw)}
}
@keyframes obstaculo {
0% {transform: translatey(0) translateX(50vw)}
100% {transform: translatey(0) translateX(0vw)}
}