Search code examples
typescriptgame-engine

Creating a FixedUpdate in Typesript


I'm working on a game-engine in typescript to learn some stuff. In Unity the way the fixed update works (in theory) is as follows:

 var physicsTimeSimulated = 0;
 var lastUpdateTime = 0;    

 while (Unity is Running)
 {
     while (physicsTimeSimulated < Time.time)
     {
         Engine.ExecutePhysicsStep();
         Engine.FixedUpdate(); // <-- sent to all objects
         physicsTimeSimulated += physicsTimeStep;
     }

     deltaTime = Time.time - lastUpdateTime;
     Engine.RenderFrame();
     Engine.Update(); // <-- sent to all objects
     lastUpdateTime = CurrentTime;

     // and repeat...
 }

What would be a good way to implement something like this in Typescript? The way I am doing the update function is as follows:

private fixedUpdateTiming: number = 1;
private lastUpdate:number = Date.now();

public Update(): void {
    while((Date.now() - this.lastUpdate) > this.fixedUpdateTiming){
      this.onAppFixedUpdate.dispatch();
      this.lastUpdate = Date.now();
    }

    this.onAppUpdate.dispatch();

    window.requestAnimationFrame(() => {
      this.Update();
    });
  }

This way, there can be many updates per fixedupdate, but I can get only one fixedupdate per update.

Thanks in advance, Steenbrink


Solution

  • Oké, nevermind, I am stupid. I will leave this here for reference.

    The way I fixed it is as follows:

    private fixedUpdateTiming: number = 20;
    private physicsTimeSimulated:number = Date.now();
    private _deltaTime: number = 0;
    private lastUpdate: number = Date.now();
    
    public Update(): void {
    
        while(this.physicsTimeSimulated < Date.now()){
    
          this.onAppFixedUpdate.dispatch();
          this.physicsTimeSimulated += this.fixedUpdateTiming;
        }
    
        this.onAppUpdate.dispatch();
    
        this._deltaTime = Date.now() - this.lastUpdate;
        this.lastUpdate = Date.now();
    
        window.requestAnimationFrame(() => {
          this.Update();
        });
      }