Problems Understanding Physics & Framerate

34 views
Skip to first unread message

cjge...@gmail.com

unread,
Apr 19, 2019, 10:04:40 PM4/19/19
to excaliburjs
Hey all,

Apologies if this is the wrong place to post this, but I have recently started a project with Electron and Excalibur for a test game I am making.

I am having this issue wherein I have added a Player and wrote some very simple code to allow the player to jump, and a global gravity acceleration to pull the player back down.

My issue is that it seems that the actor moves at different rates depending on the framerate. When I am using my linux machine, the player is sluggish and slow, but when I switch to a faster machine, the character moves faster, and even jumps markedly higher.

So I was wondering if there are any resources as to how the engine interacts with the framerate of the renderer, and if there are any strategies one could suggest to make framerate not relevant to the physics calculations of the game. https://github.com/ColeyG/items-on is my repo incase that would be helpful.

Thanks

Erik Onarheim

unread,
Apr 19, 2019, 10:44:02 PM4/19/19
to excaliburjs
The `update` method is called once per frame, given the implementation `this.velY--` will be called less frequently on a lower framerate than a higher one, decreasing velocity slower than a higher framerate.

The trick is to scale your `update` method with delta, so that update distance/velocities are consistent given different frame rates. Delta provides the time it took to render the previous frame in milliseconds.

Here is an example of scaling by delta:

//
// This implementation imparts acceleration (change in velocity) every update, meaning the longer a key is pressed the faster the character will move.
//
update(engine, delta) {
   let seconds = delta/1000; // convert from milliseconds to seconds
   let accel = 2; // 2 pixels/sec/sec
   ex.Actor.prototype.update.call(this, engine, delta);
   if (engine.input.keyboard.isHeld(ex.Input.Keys.W)) {
       this.velY = this.velY - accel * seconds;
   }
   if (engine.input.keyboard.isHeld(ex.Input.Keys.A)) {
       this.velX = this.velX  - accel * seconds;
   }
   if (engine.input.keyboard.isHeld(ex.Input.Keys.S)) {
       this.velY = this.velY + accel * seconds;
   }
   if (engine.input.keyboard.isHeld(ex.Input.Keys.D)) {
       this.velX = this.velX + accel * seconds;
   }
   this.x = this.x + this.velX;
   this.y = this.y + this.velY;
}


Reply all
Reply to author
Forward
0 new messages