JSFiddle - React, Tailwind, and code Playground

by electronoob

HTML

<canvas id=can width=800 height=300></canvas>

JavaScript

var ctx = document.getElementById('can').getContext("2d");


class Vector {
	constructor (x = 0, y = 0) {
  	this.x = x;
    this.y = y;
    }
    add (v) {
    	this.x += v.x;
      this.y += v.y;
    }
}

class Cell {
	constructor (x = 0, y = 0) {
  	this.pos = new Vector(x, y);
    this.target = new Vector();
    this.velocity = new Vector(1,1); // speed
    this.acceleration = new Vector(2,2); // amount to increase per step
  }
  update() {
		this.pos.add(this.velocity);
    this.velocity.add(this.acceleration);
    this.acceleration = new Vector(); // stop increasing per step
  }
  attract() {
		
  }
}

var points = [];
points.push (new Cell(10, 10));
points.push (new Cell(232, 140));
points.push (new Cell(10, 10, new Vector(232, 140)));


function render () {

	ctx.fillStyle = "black";
	ctx.fillRect(points[0].pos.x,points[0].pos.y,10,10);
  ctx.fillRect(points[1].pos.x,points[1].pos.y,10,10);
  ctx.fillStyle = "blue";
  ctx.fillRect(points[2].pos.x,points[2].pos.y,10,10);
  
	window.requestAnimationFrame(render);
}
render();
setInterval(()=> {
  points[2].update();
	points[2].attract();
},500);

function fly(tx,ty) {
  this.pos = new Vector(gri(0, can.width), gri(0, can.height));
  this.target = {};
  this.target.pos = new Vector(tx,ty);
  this.lpos = new Vector();
  this.acc = new Vector();
  this.vel = new Vector();
  fly.prototype.update = function() {
    this.lpos.x = this.pos.x;
    this.lpos.y = this.pos.y;
    this.pos.add(this.vel);
    this.vel.mul(0);
    this.vel.add(this.acc);
    this.acc.mul(0);
  }
  fly.prototype.attract = function() {
    var force = new Vector(this.target.pos.x, this.target.pos.y);
    force.sub(this.pos);
    distance = force.mag();
    var G = 2;
    var strength = G / (distance^2);
    strength = constrain(strength, 0, 1);
    force.setMag(strength/2);
    this.acc.add(force);
  }
}