
Clases en JavaScript
Publicado por Daniel (1 intervención) el 02/12/2015 03:54:45
Hola estoy haciendo un programita de una pelota que rebota dentro de un div.
El problema viene cuando intento añadir otra pelota y entoces solo se me mueve una de ellas.
Esta es la pagina principal:
Y esta es mi clase js.
En mi opinion deberia funcionar todo correctamente por que los alerts que hago me muestran lo esperado. Pero bueno también es la primera vez que uso una clase en javascript y no estoy muy seguro de que se haga asi.
El problema viene cuando intento añadir otra pelota y entoces solo se me mueve una de ellas.
Esta es la pagina principal:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Practica 24</title>
<script type="text/javascript" src="clasePelota.js"></script>
</head>
<body>
<div style="width:600px;height:600px;border:1px orange solid;" id="campo">
</div>
<div style="background-color:gray;width:600px; height:50px;" id="info">
</div>
<script type="text/javascript">
var pelota1 = new ClasePelota(3,2);
var pelota2 = new ClasePelota(2,2);
var intervalId = setInterval(function(){pelota1.mover();pelota2.mover()}, 100);
</script>
</body>
</html>
Y esta es mi clase js.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function ClasePelota(ix,iy){
this.x = 0;
this.y = 0;
this.minX = 0;
this.minY = 0;
this.maxX = 600;
this.maxY = 600;
this.ancho = 64
this.alto=64;
this.incrementoX = ix;
this.incrementoY = iy;
this.contrarioX = false;
this.contrarioY = false;
campo.innerHTML+="<img src='img/pelota.png' id='imgPelota"+ ix + iy +"' style='position:absolute;top:0px;left:0px;width:64px;height:64px;'>";
this.pelota = document.getElementById("imgPelota" + ix + iy);
}
ClasePelota.prototype.mover = function(){
if (!this.contrarioX){
this.pelota.style.top = this.x + this.incrementoX + "px";
this.x +=this.incrementoX;
}else{
this.pelota.style.top = this.x - this.incrementoX + "px";
this.x -=this.incrementoX;
}
if (!this.contrarioY){
this.pelota.style.left = this.y + this.incrementoY + "px";
this.y +=this.incrementoY;
}else{
this.pelota.style.left = this.y - this.incrementoY + "px";
this.y -=this.incrementoY;
}
if (this.x + this.ancho >= this.maxX){
this.contrarioX= true;
}
if (this.x <= this.minX){
this.contrarioX = false;
}
if (this.y + this.ancho >= this.maxY){
this.contrarioY= true;
}
if (this.y <= this.minY){
this.contrarioY = false;
}
info.innerHTML="Coordenadas X(" + this.x + ") - Y(" + this.y + ")";
}
En mi opinion deberia funcionar todo correctamente por que los alerts que hago me muestran lo esperado. Pero bueno también es la primera vez que uso una clase en javascript y no estoy muy seguro de que se haga asi.
Valora esta pregunta


0