I'm creating a simple gravity physics game with JavaScript. I had hardly gotten started when I realized I was probably doing something wrong, because it was going EXTREMELY slow.
I am using circular html div elements as the planets, and a small div element for the ball (it's a mini-golf game). My code looks like this:
function Ball([x, y, r]) {
this.b = document.createElement("DIV");
this.b.className = "ball";
this.b.style.width = r * 2 + "px";
this.b.style.height = r * 2 + "px";
this.b.style.left = x + "px";
this.b.style.top = y + "px";
this.start = [x, y];
this.v = [0, 0];
this.planets = levels.list[levels.currLevel][1];
// the above line just has the information for each planet
document.body.appendChild(this.b);
}
Ball.prototype.physics = function () {
var b = this;
var a = [0.25, -0.09];
this.planets.forEach(function (info) {
// change acceleration from each planet
});
b.v[0] += a[0];
b.v[1] += a[1];
b.b.style.left = (parseFloat(b.b.style.left) + b.v[0]) + "px";
b.b.style.top = (parseFloat(b.b.style.top) + b.v[1]) + "px";
setTimeout(function () {b.physics();}, 30);
}
The main problem seems to be that I am accessing CSS properties with JavaScript 33 times per second.
I am a fairly new programmer, so if there is a completely alternative way of making shapes and moving them around without dealing with DOM elements and CSS, I'd really love to know about it!
b.b.style.leftandb.b.style.topwill cause layout thrashing because you are reading from the DOM then writing to it and then reading from the DOM and writing to it again. You should batch your reads and writes together (see the link).transform: translate(x,y)astop/leftwill trigger DOM layout, which is super expensive :)