Search code examples
design-patternsgame-physics2d-games

Physics Object Double Buffering


I've been working on a little game in python using a (very) basic physics engine I wrote. The original physics code was rushed, and so I've been cleaning it up and trying to make it less terrible. Here's the problem:

I wanted to make the collision detection (using SAT algorithm) decoupled from the collision response by having physics objects store their collision response function in a variable, which allows for different objects to behave as triggers, solid objects, force fields, etc. In doing this I had to make the response consist of two method calls (one for each object in a collision) which means that one call happens after the other. This causes problems because the changes to one object have an impact on the other object's response to the collision.

I've read about double buffering being used in displaying images and thought that it might be able to be used to solve this by buffering all changes to each object somehow and applying them after they have all been calculated. I've been having trouble coming up with a clean and flexible way of doing this. Does anyone know of a good way to deal with this non-simultaneous collision response?

Edit: I've thought of having a previous and current version of each variable, but that seems ugly and would bloat the class

(sorry if this is a wordy question, I felt that the background was required to make it clear what I was trying to do)


Solution

  • Say you have 2 physics objects A and B and you have separately determined that have just collided. Your problem is that if you first work out the effect of A on B, and after that the effect of B on A, but that B will have already changed making the second part a problem!

    One possible way to to do this is to make 2 Collision objects. Each contains a copy of A and a copy of B (maybe initialised this way in the constructor). Let's say internally the collision objects are called Obj1 and Obj2.

    The main method() might be named getTheCollissionEffectOfObj1onObj2(). This would return the new version of Obj2 with its new velocity, spin etc or whatever physics you are using.

    Make 2 Collision objects one with A as Obj1 and B as Obj2 and the second one the other way around. Then call getTheCollissionEffectOfObj1onObj2() on both without worrying that A or B has changed.

    This is not too different from you suggest with variables, but it allows the impact on each object to be calculated separately because the Collision objects are constructed with copies of A and B as they were prior to the collision. When the 2 collision objects are destroyed the copies will also be destroyed.

    I don't know Python so I can't give example code, but this be doable in any OOP language.