Developing a FixedUpdate Function in TypeScript

Currently, I am delving into the world of game-engine development using TypeScript to expand my skills. The fixed update mechanism in Unity operates on a theoretical premise that involves processing physics within a while loop. Here's how it is envisioned:

 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...
 }

I am considering the best way to implement a similar behavior in TypeScript. My current approach to handling updates looks like this:

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 method allows for multiple updates per fixedupdate cycle, ensuring only one fixed update per update execution.

Thank you in advance for your insights,

Steenbrink

Answer №1

Oops, disregard that last message. I've figured out the solution and decided to leave it here for future reference.

To fix the issue, I implemented the following code snippet:

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();
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with Angular routing when attempting to directly access a specific URL path?

Seeking help with my routing setup in Angular. Using v12 of Angular. Encountering a 404 Not Found error when trying to access the direct URL for "register" at somesite.com/register. Uncertain if this is a server or Angular issue. Here is my router module ...

The onChange() function should only consider the last character typed, rather than evaluating the entire line each time

Explanation: I am utilizing the onChange function to detect when someone types the symbol @. Issue: While typing, the code currently checks the entire line each time a character is added, causing a lag in typing speed. I am looking to update the code so i ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

I'm having issues with the functionality of my code inside the ng-template and ngIf. What could be

I am facing an issue with my method that is supposed to display the specified HTML content. However, it seems like the ngIf condition within the code block is not functioning correctly. Can someone help me understand why the ngIf statement is being ignored ...

Winston's createLogger function is not defined

After setting up Jest unit tests in a TypeScript Node project, I encountered an issue where the main code broke after installing Jest with ts-node. Whenever I try to run npm test or npm start, I receive the following error: [nodemon] watching extensions: t ...

TypeScript mistakenly infers the incorrect type for AbstractControl when used with a generic type_declaration

My InnerComponent requires a FormArray as input, and in order to access the type of the controls within the array, I have introduced a type parameter called ControlValue. The input is declared to be of type FormArray<AbstractControl<ControlValue>& ...

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

Typescript's async function failing to execute properly

I'm currently facing an issue with my code and I'm a bit puzzled as to where the problem lies. The console is displaying the correct data for this.allNominations, but it appears that the third for-loop is not being executed at all. As a result, t ...

What is the best way to incorporate this in a callback function?

Utilizing a third-party component requires creating an object for configuration, such as itemMovementOptions in the given code sample. export class AppComponent implements OnInit { readonly itemMovementOptions = { threshold: { horizontal: ...

Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with: var classn ...

Absolute imports in create-react-app do not function properly when using yarn v2 workspaces alongside typescript

I am currently utilizing yarn v2 workspaces, and within my workspaces, I have a frontend project built using create-react-app / react-scripts. My goal is to enable absolute imports in the frontend application so that I can simply do things like import Butt ...

Using a promise as a filter callback in JavaScript: A guide

UPDATE: The solution can be found below I have a multitude of components that need to be filtered based on certain properties, but I am encountering an issue where I cannot resolve the promise before using it in the Array.filter() method. Here is my curr ...

Using Angular2 to perform search functions within the Loopback framework

Can anyone assist me with implementing a "wildcard" query using loopback to search data from the database in my angular2 project? Thank you in advance for your help. This is the query I am trying to use: this.model.find({ "where": { "wildcard ...

Having trouble getting tsserver-plugins to function properly in either Atom or VSC

My team and I are on a mission to enhance our Angular 2 templates with code completion, similar to what is showcased in this gif. To achieve this goal, we require: tsserver-plugins coupled with tslint-language-service and @angular/language-service We ...

Troubleshooting Nested Handlebars Problem

After creating a customized handlebar that checks for equality in this manner: Handlebars.registerHelper('ifEquals', (arg1, arg2, options) => { if (arg1 == arg2) { return options?.fn(this); } return options?.inverse(t ...

Troubleshooting React Typescript and Bootstrap - Issues with Collapse Component

I've encountered an issue in my React TypeScript app with Bootstrap 5. The app was set up using create-react-app and Bootstrap was added with npm i bootstrap. There is a button in the app that triggers the visibility of some content, following the ex ...

Is there a method to globally import "typings" in Visual Code without having to make changes to every JS file?

Is there a method to streamline the process of inputting reference paths for typings in Visual Studio Code without requiring manual typing? Perhaps by utilizing a configuration file that directs to all typings within the project, eliminating the need to ...

Verify the presence of identical items in the array

I have been attempting to identify any duplicate values within an array of objects and create a function in ES6 that will return true if duplicates are found. arrayOne = [{ agrregatedVal: "count", value: "Employee Full Name" }, { agrrega ...

Group of objects containing an inner group of objects

Here is an array of objects that I am working with: let prova: ActiveRoute[] = [ { path: '/Root', method: 'GET', children: [ { path: '/Son', method: 'GET', chi ...

Once StoreModule.forFeature(...) has been included, the stored data becomes inaccessible

I am currently working on multiple projects within a single Angular 8 app... Previously, I had @ngrx/store implemented in only one project, but now I have added @ngrx/store to every project. Due to having multiple stores, I now need to import StoreModule.f ...