jaipack17 / Nature2D

A 2D physics engine for Roblox. Create versatile physics simulations and mechanics with GUIs!
https://jaipack17.github.io/Nature2D/
MIT License
147 stars 8 forks source link

Optimizations #22

Closed jaipack17 closed 2 years ago

jaipack17 commented 2 years ago

I'll be making some major and minor optimizations to the whole library where necessary. These would include optimizations to collision detection, updating and rendering points and constraints, querying of rigid bodies during collision detection, collision related events of the Engine and RigidBodies, object creation and more.

The reason these optimizations are necessary is because of how the collisions between rigid bodies are not "rigid" enough, or in simple words - the rigid bodies are not really "rigid". They act more like soft bodies. And, the cause of this is because of the extremely low amount of iterations performed each for calculating and rendering physics. You may notice, rigid bodies start clipping into each other when their numbers are increased, since there is an exponential spike in the calculations that take place causing frame drops.

Why do more iterations matter? Currently, physics calculations and updates to physics objects are performed just once every RenderStepped. During low frame rates or even high frame rates, collisions tend to happen in between 2 rendered frames, commonly at low frame rates since the delta time is higher. This means, less collision checks and responses are performed and the physics objects are updated and rendered at low frequency causing them to clip into each other. Doing the same task multiple times helps in this case. For example, performing the physics calculations and updating the physics objects 6 times each frame means that there are 6 iterations being made. This maintains the "rigidness" of these physics objects and keeps them stable even at low frame rates.

A comparison between just 1 iteration and multiple iterations of physics calculations. From a matter.js demo.

1 Iteration Multiple Iterations
Rigid bodies clip into each other very often. The rigid bodies don't clip into each other very often.

Hopefully these optimizations will help me add more iterations to the physics calculations to make the rigid bodies actually rigid. At present, this is not possible. More iterations equals more lag.

This pull request will remain a draft until all changes have been made and revised. I look forward for reviews, feedback and suggestions if any.

Progress: