I have been writing a small particle plugin since I want to learn how physics works for games. Now I have tried to get this as clean as I possible could but It feels something is missing. Am I repeating too much code? Could this be improved in any way such as in performance?
https://jsfiddle.net/zdufwLv6/
new explodeLayer({
particles: 17, xSpread: 5, ySpread: 20, colorIndex: 3, radius: 0, radiusMax: 100, x: 0, y: 0
})
function explodeLayer(obj) {
var self = this;
this.elem = document.getElementsByTagName('div');
this.particle = [];
this.radius = obj.radius;
this.color = ['red', 'yellow', 'cyan', 'orchid']
this.interval = 2 * Math.PI / obj.particles;
this.init = function() {
this.create();
this.blast();
}
this.create = function() {
for(var i = 0; i < obj.particles; i++) {
document.body.appendChild(document.createElement('div'));
this.elem[i].style.background = this.color[obj.colorIndex];
this.particle.push(new this.Properties(this.interval * i, obj.x, obj.y));
this.updatePosition(i);
}
}
this.Properties = function(angle, x, y) {
this.angle = angle;
this.x = x;
this.y = y;
this.vy = y;
this.vx = y;
}
this.updatePosition = function(index) {
this.elem[index].style.left = this.particle[index].x + 'px';
this.elem[index].style.top = this.particle[index].y + 'px';
}
this.move = function() {
for(var i = 0; i < this.particle.length; i++) {
this.particle[i].vy += 0.4;
this.particle[i].x += this.particle[i].vx;
this.particle[i].y += this.particle[i].vy;
this.updatePosition(i);
}
requestAnimationFrame(function() {
self.move.call(self);
});
}
this.blast = function() {
for(var i = 0; i < this.particle.length; i++) {
this.particle[i].x = Math.round(window.innerWidth) / 2 + this.radius * Math.cos(this.particle[i].angle);
this.particle[i].y = Math.round(window.innerHeight) / 2 + this.radius * Math.sin(this.particle[i].angle);
this.particle[i].vx = obj.xSpread * Math.cos(this.particle[i].angle);
this.particle[i].vy = obj.ySpread * Math.sin(this.particle[i].angle);
this.updatePosition(i);
}
requestAnimationFrame(function() {
self.move.call(self);
});
}
this.init();
}
html, body { background: rgb(30, 30, 30)}
div { padding: 8px; position: absolute; border-radius: 100%}