バウンスボールのクラス

覚え書き

・力はフレーム毎に足し合わせる。
・forceメソッドが他のボールに力を加えるメソッドである。
・イニシャライズで足し合わせた力をゼロに戻す。
レンダリングは二種類用意した。
・ボール同士が、色を変える、のような機能を実装しようとしたが、未完。

class BounceBall {
  constructor(x, y, r, m, col) {

    this.x = x;
    this.y = y;
    this.vx = random();
    this.vy = random();
    this.fx = 0;
    this.fy = 0;

    this.life = 0;
    this.own_color = [0,0,250];
    this.your_color = [250,0,0];
    this.color = col;

    this.m = m;
    this.r = r;
    this.w = this.r*2;
    this.h = this.r*2;

  }
  
  init(){
    
    this.fx = 0;
    this.fy = 0;
    this.color = this.own_color;

  }

  update(){

    this.x += this.vx;
    this.y += this.vy;

    this.vx += this.fx/this.m;
    this.vy += this.fy/this.m;

    this.life += 1;


  }
  
  force(){
    
    balls.forEach(b => {
      
      let l = dist(b.x,b.y,this.x,this.y);
      let l0 = this.r + b.r;
      
      if(l-l0 < 0){
        
        let vec = createVector(b.x-this.x,b.y-this.y);
        vec.normalize();
        vec.mult(abs(l-l0));
        
        b.fx += k*vec.x;
        b.fy += k*vec.y;
        
        
      };
      
    });
    
  }

  reflect_wall(){

    if (this.y < this.r) {
      this.vy = -this.vy*k_2;
      this.y = this.r;
    }
    if (this.y > height - this.r) {
      this.vy = -this.vy*k_2;
      this.y = height - this.r;
    }
    if (this.x < this.r) {
      this.vx = -this.vx*k_2;
      this.x = this.r;
    }
    if (this.x > width - this.r) {
      this.vx = -this.vx*k_2;
      this.x = width - this.r;
    }

  }

  render(){
    push();
    fill(this.color);
    translate(this.x, this.y);
    strokeWeight(1);
    circle(0, 0, this.r*2);
    pop();
  }

  render_2(){
    push();
    drawingContext.shadowBlur = 12;
    let wh = "rgb(248,240,240)";
    let bl = "rgb(31,31,242)";
    drawingContext.shadowColor = wh;
    translate(this.x, this.y);
    strokeWeight(1);
    stroke(wh);
    fill(this.color);
    circle(0, 0, this.r*2);
    pop();
  }

}