JSFiddle - React, Tailwind, and code Playground
by Darby Rathbone
CSS
html,body{
margin:0px;
padding:0px;
overflow:hidden;
}
canvas{
width:auto;
height:auto;
}
JavaScript
var Vector = (function () {
var v = Object.create(null);
v.add = function (x, y) {
if (x.type == 'vector') {
y = x.y;
x = x.x;
}
this.x += x;
this.y += y;
return this;
};
v.mag = function(){
return Math.sqrt(this.x*this.x+this.y*this.y);
};
v.dot = function(v){
var m1= this.mag(),m2 = v.mag(), t = this.clone().scale(1/m1), v2 = v.clone().scale(1/m2);
return t.x*v2.x+t.y*v2.y;
};
v.div = function (s){
this.x /=s;
this.y /=s;
return this;
};
v.sub = function (x, y) {
if (x.type == 'vector') {
y = x.y;
x = x.x;
}
this.x -= x;
this.y -= y;
return this;
};
v.dot = function(p){
return this.x*p.x+this.y*p.y;
};
v.scale = function (s) {
this.x *= s;
this.y *= s;
return this;
};
v.clone = function () {
return vector(this.x, this.y);
};
v.set = function (x, y) {
if (x.type == 'vector') {
y = x.y;
x = x.x;
}
this.x = x;
this.y = y;
return this;
};
v.toString = function () {
return [this.x, this.y];
};
v.type = "vector";
return v;
})();
var vector = function (x, y) {
var V = Object.create(Vector);
V.set(x, y);
return V;
};
var Ball = function () {
var b = Object.create(null);
b.position = vector(0, 0);
b.collisions = [];
b.radius = 0;
b.noforce = vector(0,0);
b.velocity = vector(0, 0);
b.force = vector(0, 0);
b.addForce = function (f) {
this.force.add(f);
};
b.moveBy= function(x,y){
this.noforce.add(x,y);
};
b.withinBounds = function (x1, y1, x2, y2) {
if (x1.type == 'vector') {
x2 = y1.x - this.radius;
y2 = y1.y - this.radius;
y1 = x1.y +...