I'm doing a simulator of a bouncing ball and I wanted to add things like a goal and that if you get scoring goal and points.
But in the case of the "Red team" it marks two points because the if cycle is done twice, which I do not understand how to prevent this from happening.
Everything is fine with "blue" the logic is if x == 0 && y >= 125 && y <= 175
marks goal 1 point, but in case of "red team" if x == 480 && y >= 125 && y <= 175
in this case nothing happens because 480 can not be, it is outside the container (I do not know why) then, the size of the ball is always less, in this case 5px.
Then the logic is si x == 475 && y >= 125 && y <= 175
and now if you score goal, but twice, 2 points.
The if cycle is met twice because the 475 is repeated and it is fulfilled but if I put yes x == 476 && y >= 125 && y <= 175 ó x == 477
.. nothing happens.
Can you help me explain what's going on? Because it does not work, why do not you accept the 480px? I already tried to put instead of 5px to 1px but it is the same, it marks twice (it passes twice by the same coordinate 475).
Annex code:
// Simulador 6
var x = 0;
var xLimite = 0;
var y = 0;
var yLimite = 0;
var azul = 0,
rojo = 0;
function jugar() {
var ciclo = setInterval(mover, 30);
}
function mover() {
//EJE X
if (xLimite == 0) {
document.getElementById('pelota').style.marginLeft = x + "px";
x += 5;
if (x >= 480) {
xLimite = 1;
}
}
if (xLimite == 1) {
document.getElementById('pelota').style.marginLeft = x + "px";
x -= 5;
if (x <= 0) {
xLimite = 0;
}
}
//EJE Y
if (yLimite == 0) {
document.getElementById('pelota').style.marginTop = y + "px";
y += 5;
if (y >= 280) {
yLimite = 1;
}
}
if (yLimite == 1) {
document.getElementById('pelota').style.marginTop = y + "px";
y -= 5;
if (y <= 0) {
yLimite = 0;
}
}
//JUEGO 500x por 300y
var audio = document.getElementById('audio');
if (x == 0 && y >= 125 && y <= 175) {
azul += 2;
audio.play();
}
if (x == 475 && y >= 125 && y <= 175) {
rojo += 1;
audio.play();
}
document.getElementById('marcador').innerHTML = "Equipo Azul: " + azul + " Equipo Rojo: " + rojo;
}
/* Simulador 6 */
.publicoFutbol {
width: 500px;
height: 100px;
margin-left: 230px;
}
#contenedor {
background-image: url("http://netliguista.com/img/org/campo-futbol.png");
background-repeat: no-repeat;
background-size: 100% 100%;
width: 500px;
height: 300px;
margin: auto;
background-color: #fff;
}
#pelota {
width: 20px;
height: 20px;
}
#audio {
display: none;
}
<a name="sim6"></a>
<article class="sim6">
<header>
<h3>Simulador 6: ¡Juego Futbol!</h3>
</header>
<p class="usuario" id="saludo5">Hola </p>
<p class="usuario"> este es un simulador de pelota <br><br> Como jugar:</p>
<section>
<div id="contenedor">
<img id="pelota" src="https://www.tenvinilo.com/vinilos-decorativos/img/preview/vinilo-infantil-pelota-futbol-color-1399.png">
</div>
<button id="jugar" onclick="jugar()">GO</button>
<label id="marcador"> - </label>
<audio id="audio">
<source src="musica/gol.aac" type="audio/aac">
</audio>
</section>
</article>