Alright, let's program up some gravity!
First we'll make two objects. The first object ({}) is velocity which will have its own x and y variables that will be applied to the particle object's x and y variables.
Since we are creating an array of this object that will have random numbers, we loop through each item and assign it a base value. Then loop again to assign it the random values to place particles all over the screen.
Now that we're set up, we start the timer function and apply force to each particle by calculating the force, multiplying it by the velocity, and adding it to the particle coordinate.
Our center of gravity is stationary so we didn't have to really set anything up for that but setting its coordinates as a variable means that we're doing six less calculations every time the screen refreshes. This is a very memory intensive calculation and easily gets out of control when you increase the particleIndex so anything you can do to increase efficiency is helpful in making sure the animation is smooth and ensuring that it can be rendered with older hardware.
function drawShapes() {
var particleIndex = 1, particle = {}, velocity = {}, gravityx = w / 2, gravityy = h / 2; for (z = 0; z < particleIndex; z++) { particle[z] = { x: Math.floor(Math.random() * w), y: Math.floor(Math.random() * h), color: randomColor() }; velocity[z] = { x: Math.floor((Math.random() * 5) - 5), y: Math.floor((Math.random() * 5) - 5) }; }
setInterval(function() {
clearScreen();
for (z = 0; z < particleIndex; z++) {
var distance = Math.pow((particle[z].x - gravityx), 2) + Math.pow((particle[z].y - gravityy), 2),
f = (1 / Math.sqrt(distance));
velocity[z].x += (particle[z].x - gravityx) * f;
velocity[z].y += (particle[z].y - gravityy) * f;
particle[z].x -= velocity[z].x;
particle[z].y -= velocity[z].y;
drawCircle(gravityx, gravityy, 60, "black");
drawCircle(particle[z].x, particle[z].y, 10, particle[z].color);
}
}, 50);
}