1

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!

2
  • In addition to using an animation frame, your two lines where you set b.b.style.left and b.b.style.top will 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). Commented Jun 18, 2019 at 3:19
  • Consider using transform: translate(x,y) as top/left will trigger DOM layout, which is super expensive :) Commented Jun 20, 2019 at 16:24

1 Answer 1

2

Use requestAnimationFrame instead of setTimeout will get better performance. BTW, it's best to use canvas to run your game, it's super fast. You can take a look at PIXI.js or EaselJS.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I found this article and it was very good and concise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.