Gravity Simulation Code
const BACKGROUND = "black";
const FOREGROUND = "green";
const background = document.getElementById("background");
const FPS = 60;
class point {
constructor({ x, y, vx, vy, size = 20 }) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.size = size;
}
paint() {
ctx.fillStyle = FOREGROUND;
ctx.fillRect(
this.x - this.size / 2,
this.y - this.size / 2,
this.size,
this.size,
);
}
update() {
const centerX = background.width / 2;
const centerY = background.height / 2;
let dx = centerX - this.x;
let dy = centerY - this.y;
let distance = Math.sqrt(dx * dx + dy * dy);
const gravity = 0.05;
if (distance > 1) {
this.vy += (dy / distance) * gravity;
this.vx += (dx / distance) * gravity;
}
this.x += this.vx;
this.y += this.vy;
if (this.x + this.size / 2 >= background.width || this.x - this.size / 2 <= 0) {
this.vx *= -1;
}
if (this.y + this.size / 2 >= background.height || this.y - this.size / 2 <= 0) {
this.vy *= -1;
}
}
}