0

molestando, lo que sucede es que tengo una molecula y ya tengo la colision con el canvas para que estas moleculas no se salgan y reboten, el problema lo tengo que nadamas la colision se genera en mi atomo rojo (circulo rojo) y no en el blanco, les agradeceria su ayuda en esta ocación

JS

class AtomoClass{
    constructor(posx,posy,color,radio){
        this.posx=posx;
        this.posy=posy
        this.color=color;
        this.radio=radio;
        this.inicia=0;
        this.termina=2*Math.PI;
        this.angle = Math.random()*(2*Math.PI);
        this.movimientox = Math.cos(this.angle);
        this.movimientoy = Math.sin(this.angle);
        this.enlace = null;
    }
}
var atomos=[];
var ballRadius = 30;
var otroballRadius=20;
var canvasRecipiente = document.getElementById("recipiente");
var ctx = canvasRecipiente.getContext("2d");

for (var i= 0; i < 20; i++) {

    var atomoR = new AtomoClass(ballRadius+(Math.random()*(recipiente.width-(2*ballRadius))),(ballRadius+(Math.random()*(recipiente.height-(2*ballRadius)))),'red',ballRadius);
    atomos.push(atomoR);
    var atomoB = new AtomoClass(otroballRadius+(Math.random()*(recipiente.width-(2*otroballRadius))),(otroballRadius+(Math.random()*(recipiente.height-(2*otroballRadius)))),'white',otroballRadius);
    atomoB.enlace = atomoR;
    atomos.push(atomoB);

}
function atomoPinta(){
for (var j = 0; j < atomos.length; j++){
    var defaultX = atomos[j].posx;
    var defaultY = atomos[j].posy;

        if(atomos[j].enlace != null){
        defaultX = atomos[j].enlace.posx+15;
        defaultY = atomos[j].enlace.posy+25;
        }
        ctx.beginPath();
        ctx.arc(defaultX,defaultY,atomos[j].radio,atomos[j].inicia,atomos[j].termina);
        ctx.fillStyle = atomos[j].color;
        ctx.stroke();
        ctx.fill();
        ctx.closePath();
    }
}
function draw(){
    ctx.clearRect(0, 0, recipiente.width, recipiente.height);
    atomoPinta();

    for (var b = 0; b < atomos.length; b++) {

        if(atomos[b].posx + atomos[b].movimientox > recipiente.width-atomos[b].radio || atomos[b].posx + atomos[b].movimientox < atomos[b].radio) {
        atomos[b].movimientox = -atomos[b].movimientox;
        }
        if(atomos[b].posy + atomos[b].movimientoy > recipiente.height-atomos[b].radio || atomos[b].posy + atomos[b].movimientoy < atomos[b].radio) {
        atomos[b].movimientoy = -atomos[b].movimientoy;
        }
        atomos[b].posx += atomos[b].movimientox;
        atomos[b].posy += atomos[b].movimientoy;        
    }

    requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

1 respuesta 1

0

Hice algunos cambios en tu código pero seguro que podrás reconocer tu código. Además de la clase que construye el átomo, he creado otra clase que construye la molécula. Esta clase tiene 2 átomos.

No guardo los átomos en un array sino las moléculas.

En lugar de calcular el movimiento de cada átomo calculo el movimiento del centro de la molécula.

La clase de la molécula tiene un método colision() que cambia el sentido del movimiento si alguno de los dos átomos toca el borde del canvas.

He dejado tu manera de calcular la velocidad, pero esto puede generar en ocasiones una velocidad = 0.

Espero que esto sea lo que deseabas hacer.

var canvasRecipiente = document.getElementById("recipiente");
var ctx = canvasRecipiente.getContext("2d");
var cw = (canvasRecipiente.width = window.innerWidth);
var ch = (canvasRecipiente.height = window.innerHeight);
var num_moleculas = 2;

var moleculas = [];
var ballRadius = 30;
var otroballRadius = 20;

class AtomoClass {
  constructor(posx, posy, color, radio) {
    this.posx = posx;
    this.posy = posy;
    this.color = color;
    this.radio = radio;
    this.inicia = 0;
    this.termina = 2 * Math.PI;
  }

  pinta() {
    ctx.beginPath();
    ctx.arc(this.posx, this.posy, this.radio, this.inicia, this.termina);
    ctx.fillStyle = this.color;
    ctx.stroke();
    ctx.fill();
    ctx.closePath();
  }
}

class Molecula {
  constructor() {
    let r_rojo = ballRadius + ballRadius * Math.random();
    let r_blanco = r_rojo / 2;
    
    this.centrox = 2*r_rojo + Math.random() * (recipiente.width - 4 * r_rojo);
    this.centroy = 2*r_rojo + Math.random() * (recipiente.height - 4 * r_rojo);

    this.angulo = Math.random() * 2 * Math.PI;
    this.movimientox = Math.cos(this.angulo);
    this.movimientoy = Math.sin(this.angulo);


    let posx_rojo = this.centrox + r_rojo * Math.cos(this.angulo);
    let posy_rojo = this.centroy + r_rojo * Math.sin(this.angulo);
    let posx_blanco = this.centrox + r_blanco * Math.cos(Math.PI + this.angulo);
    let posy_blanco = this.centroy + r_blanco * Math.sin(Math.PI + this.angulo);

    this.atomoR = new AtomoClass( // atomo rojo
      posx_rojo, //posx
      posy_rojo, //posy
      "red", //color
      r_rojo
    ); //radius

    this.atomoB = new AtomoClass( // atomo blanco
      posx_blanco, //posx
      posy_blanco, //posy
      "white", //color
      r_blanco
    ); //radius);//radius
  }

  pinta() {
    this.atomoR.posx = this.centrox + this.atomoR.radio * Math.cos(this.angulo);
    this.atomoR.posy = this.centroy + this.atomoR.radio * Math.sin(this.angulo);
    this.atomoB.posx =
      this.centrox + this.atomoB.radio * Math.cos(Math.PI + this.angulo);
    this.atomoB.posy =
      this.centroy + this.atomoB.radio * Math.sin(Math.PI + this.angulo);
    this.atomoR.pinta();
    this.atomoB.pinta();
  }

  movimiento() {
    this.centrox += this.movimientox;
    this.centroy += this.movimientoy;
  }

  colision() {
    if (
      this.atomoR.posx < this.atomoR.radio ||
      this.atomoR.posx > cw - this.atomoR.radio ||
      this.atomoB.posx < this.atomoB.radio ||
      this.atomoB.posx > cw - this.atomoB.radio
    ) {
      this.movimientox *= -1;
    }

    if (
      this.atomoR.posy < this.atomoR.radio ||
      this.atomoR.posy > ch - this.atomoR.radio ||
      this.atomoB.posy < this.atomoB.radio ||
      this.atomoB.posy > ch - this.atomoB.radio
    ) {
      this.movimientoy *= -1;
    }
  }
}

for (let i = 0; i < num_moleculas; i++) {
  moleculas.push(new Molecula());
}

function draw() {
  ctx.clearRect(0, 0, cw, ch);
  for (let i = 0; i < moleculas.length; i++) {
    let molecula = moleculas[i];
    molecula.colision();
    molecula.movimiento();
    molecula.pinta();
  }

  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
body,canvas{margin:0; padding:0}
<canvas id="recipiente"></canvas>

5
  • explicame porque, this.centrox y this.centroy, entiendo entre que valores esta pero como deduciste esa formula, se utiliza esa misma formula si es que quiero añadir mas atomos? el 26 sep. 2018 a las 16:41
  • 2*r_rojo es el diámetro del circulo rojo, de los dos el más grande. El centro tiene que estar dentro del recipiente pero ningún circulo no puede salirse del canvas. Si el circulo rojo ( que es el más grande ) no sale el blanco tampoco.
    – enxaneta
    el 26 sep. 2018 a las 16:59
  • Conque empiezo a poner centros a 2*r_rojo del borde izquierdo, y me voy todo el ancho del canvas pero paro a 2*r_rojo del borde derecho. Conque necesito un número aleatorio entre 0 y recipiente.width - 2*2 * r_rojo más 2 * r_rojo. Así escrito parece muy lioso. Si lo dibujas en un papel será más claro.
    – enxaneta
    el 26 sep. 2018 a las 17:05
  • ya me quedo claro esa parte, pero que sucede si quiero separar los circulos? y tenga sus colisiones independientemente el 26 sep. 2018 a las 18:10
  • Pruebalo, y si no sale haz otra pregunta
    – enxaneta
    el 26 sep. 2018 a las 19:41

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.