JSFiddle - React, Tailwind, and code Playground

by John Doe

JavaScript

let cvs = document.createElement('canvas');
cvs.width=600;
cvs.height=300;
document.body.appendChild(cvs);
let ctx = cvs.getContext('2d');
const scale = 10;
// ballState: [ball]
// ball: [position, velocity]
var ballState = [
{p:[1,1],  v:[1, 1], c:0},
{p:[10,10],v:[-1,-1], c:0},
{p:[1,10], v:[1,-1], c:0},
{p:[10,1], v:[-1,1], c:0}
]
/*
ballState = [
  {p:[10, 10], v:[1, 0], c:0},
  {p:[20, 11], v:[-2, 0], c:0},
  {p:[30, 10], v:[1, 0], c:0},
  {p:[40, 10], v:[-1, 0], c:0},
]
//*/
//*
ballState = [];
var m = 6;
for(let k=0;k<m;k++){
  let a = 2*Math.PI*k/m;
  let x = [Math.cos(a), Math.sin(a)];
  ballState.push({
    p:[scale*(x[0]+1), scale*(x[1]+1)],
    v:[-x[0],-x[1]],
    c:0
  })
}
//*/
var phase = 0;
function stepState(ballState){
	//compute all collisions
  let collisions = []; //collision: [(i, j), time]
  for(let i=0; i<ballState.length; i++){
    for(let j=0; j<i; j++){
      if(i == j){continue;} //ball cannot collide with itself
      //console.log(`${i},${j}`)
      let a = ballState[i];
      let b = ballState[j];
      let times = collisionTimes(a.p, a.v, b.p, b.v);
      times.sort((a,b)=>a-b);
      console.log(`:35 collision times ${times}`)
      for(let t of times){
        console.log(`stepState i=${i} j=${j} t=${t}`)
        if(t >= 0){  //only consider future collisions
          //to avoid numerical issues
          //also make a check whether the 
          //collision has been computed yet: 
          //would they diverge in the near future? 
          //consider derivatife of distance
          let pba = [a.p[0]-b.p[0], a.p[1]-b.p[1]];
          let vba = [a.v[0]-b.v[0], a.v[1]-b.v[1]];
          let dot = pba[0]*vba[0] + pba[1]*vba[1];
          if(dot < 0){ //still colliding
          	console.log('touching and colliding')
            collisions.push([[i,j], t]);
            break;
          } // else continue
          console.log('touching and diverging')
        } // if t
      }//for t
    }//for j
  }//for i
  //find closest in...