0
\$\begingroup\$

I am currently making a small 2D game and I am trying to implement some basic 2D physics. I currently have a list of around 100 PhysicsObjects which I loop through every frame in order to update and apply forces to that object based on user input. The basic code is as follows:

accumulator = 0
dt = 0.01

while running:
    for each object in PhysicsObjects:
        update object

    accumulator += time between last frame and current frame

    while accumulator >= dt:
        for each object in PhysicsObjects:
            resolve forces to get new position of object based on dt
        accumulator -= dt
    
    for each object in PhysicsObjects:
        render the object

I was going to resolve the forces and calculate the new position in the update method of each object, but I was told the dt was necessary in order to make the movement and physics independent of frame rate, which is why it is in a separate loop. I also can't update the objects in the physics engine loop as the update method needs to occur every frame.

This already seems incredibly inefficient, and I haven't even started to test for collisions or anything else more in the physics engine. Is there a better way to structure this where I don't need to loop through every object again in order to calculate their new position?

\$\endgroup\$
5
  • \$\begingroup\$ Do you have any particular objects you might be able to exclude, like objects that are static or sleeping? \$\endgroup\$
    – DMGregory
    Commented Dec 23, 2020 at 17:43
  • \$\begingroup\$ @DMGregory Yes, I have a few that only do something when hit by the player, but what do I do with these? \$\endgroup\$
    – James L
    Commented Dec 23, 2020 at 18:06
  • \$\begingroup\$ You might be interested in a "sleep" optimization for that case. \$\endgroup\$
    – DMGregory
    Commented Dec 23, 2020 at 19:20
  • \$\begingroup\$ Thanks, that seems like a great optimization! \$\endgroup\$
    – James L
    Commented Dec 23, 2020 at 22:06
  • \$\begingroup\$ physics programmer here, you want what is known as a broadphase step in collision detection to quickly and efficiently reduce the number of actual collision tests to a subset of objects which may possibly collide. If you would like a detailed explanation, let me know and i will be happy to answer your question. \$\endgroup\$
    – Jon
    Commented Dec 25, 2020 at 1:18

0

You must log in to answer this question.

Browse other questions tagged .