
Detectar choque entre circulos canvas HTML5
Publicado por Isaac (5 intervenciones) el 28/02/2015 21:47:01
Quisiera saber cómo puedo hacer que, teniendo dos círculos, como objetos independientes, los cuales están rebotando dentro del canvas de forma libre, cuando se encuentren reboten entre ellos y cambien su dirección.
Adjunto mi código JS para mi canvas, para que sepan cómo lo tengo planteado, si no se lee bien aquí, dejo adjunto el archivo JS, gracias:
Adjunto mi código JS para mi canvas, para que sepan cómo lo tengo planteado, si no se lee bien aquí, dejo adjunto el archivo JS, gracias:
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Función que crea un circulo.
function circle(x, y, r, color) {
contexto.fillStyle = color;
contexto.beginPath();
contexto.arc(x, y, r, 0, Math.PI*2, true);
contexto.closePath();
contexto.fill();
}
// Función que crea un rectangulo.
function rect(x, y, w, h, color) {
contexto.fillStyle = color;
contexto.fillRect(x, y, w, h);
}
// Función que crea un objeto pelota
function Pelota(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.dx = 1;
this.dy = 1.1;
this.speed = 2;
this.center = this.r/2;
this.update = function() {
if (this.x+this.center > ancho_rectangulo || this.x-this.center < 0) {
this.dx = -this.dx;
}
if (this.y+this.center > alto_rectangulo || this.y-this.center < 0) {
this.dy = -this.dy;
}
this.x += this.dx * this.speed;
this.y += this.dy * this.speed;
}
this.draw = function() {
circle(this.x, this.y, this.r, this.color);
}
}
//Función que actualiza y dibuja la pelota.
function gameLoop() {
limpiar();
// Si (pelota.x > width) entonces clearInterval(intervalId);
pelota1.update();
pelota1.draw();
pelota2.update();
pelota2.draw();
}
// Función que limpia los pasos de la pelota
function limpiar() {
contexto.fillStyle = "grey";
rect(0, 0, ancho_rectangulo, alto_rectangulo);
}
// Función para iniciar el programa
function init() {
canvas = document.getElementById("miCanvas");
contexto = canvas.getContext("2d");
ancho_rectangulo = canvas.width;
alto_rectangulo = canvas.height;
pelota1 = new Pelota(50, 50, 10, "silver");
pelota2 = new Pelota(50, 250, 10, "black");
setInterval(gameLoop, 20); //Llama a la función gameLoop cada 20 milisegundos de forma indefinida.
}
window.onload = init;
// Variables.
var canvas, contexto, ancho_rectangulo, alto_rectangulo;
- Archivo-JS.rar(1,0 KB)
Valora esta pregunta


0