BobTheFarmer / VACTQ-Typing-Game

Apache License 2.0
0 stars 1 forks source link

Game Control Loop #5

Open BobTheFarmer opened 1 year ago

BobTheFarmer commented 1 year ago

Overview/goal of this code

The frontend needs a central script to update the positions of the cars from the API data. It's also important that this script is well-connected both to the animation and the backend, acting as the connector.

Use of OOP

I want to store the position data in an object that mirrors the backend objects. This will make the process of updating the player positions easier. The Player object needs to do four things:

  class Player {
      constructor(index) {
          this.progress = 0;
          this.index = index;
      }

      reset() {
          this.progress = 0;
      }

      update(positionData) {
          this.progress = positionData[this.index];
      }
  }

Notice how the update takes all the JSON data and interprets it rather than just take its own data. That will make the code more concise and easier to write later.

Challenges from writing this code before other parts of the project are ready

This code will serve as the 'glue' connecting the backend to the animations on the frontend. However, in order to test this code before those two parts were ready, I had to be creative with where data is received and sent.

function getAPIData() {
    return [10, 0, 20,30];
}

Ticking system

To avoid inconsistencies in how fast positions are updated depending on connection speed, I used a ticking system to only call the API over some interval. A constant is used to make this interval easily adjustable.

const tickRate = 1000;
function tick() {
    updatePositions(getAPIData());

    //Update cars animations

}

let interval = setInterval(tick, tickRate);