JSFiddle - React, Tailwind, and code Playground
by Jani Bolkvadze
CSS
body {
overflow: hidden;
}
.dot {
position: absolute;
border-radius: 5px;
background: black;
width: 10px;
height: 10px;
top:10px;
left:10px;
}
JavaScript
$(function() {
var GRAVITY = new Vector(0, 9.81);
var FRICTION = 0.85;
var world = {
x1: 0,
y1: 0
};
$(window).resize(function() {
world.x2 = $(window).width();
world.y2 = $(window).height();
}).trigger("resize");
function Ball() {
this.position = new Point(0, 0);
this.output = $("<div>").addClass("dot").appendTo("body");
this.velocity = new Vector(-1, 0);
}
Ball.prototype = {
remove: function() {
this.output.remove();
},
move: function() {
// apply gravity
this.velocity = this.velocity.add(GRAVITY.scale(0.1));
// collision detection against world
if (this.position.y > world.y2) {
this.velocity.x2 = -this.velocity.x2 * FRICTION;
this.position.y = world.y2;
} else if (this.position.y < world.y1) {
this.velocity.x2 = -this.velocity.x2 * FRICTION;
this.position.y = world.y1;
}
if (this.position.x < world.x1) {
this.velocity.x1 = -this.velocity.x1 * FRICTION;
this.position.x = world.x1;
} else {
if (this.position.x > world.x2) {
this.velocity.x1 = -this.velocity.x1 * FRICTION;
this.position.x = world.x2;
}
}
// update position
this.position.x += this.velocity.x1;
this.position.y += this.velocity.x2;
// render
this.output.css({
left: this.position.x,
top: this.position.y
});
}
};
var balls = [];
balls.push(new Ball());
// animation loop
setInterval(function() {
balls.forEach(function(ball) {
ball.move();
});
}, 25);
// create new balls with velocity
var start;
});
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
relative: function(to) {
return new Vector(to.x - this.x, to.y - this.y);
},
distance: function(to) {
return Math.sqrt(Math.pow(this.x - to.x, 2) + Math.pow(this.y - to.y, 2));
}
};
function Vector(x1, x2) {
this.x1 = x1;
this.x2 = x2;
}
Vector.prototype = {
add: function(other) {
return new Vector(this.x1 + other.x1, this.x2 + other.x2);
},
scale: function(by) {
return...