Maxim Gershkovich
Maxim Gershkovich

Reputation: 47149

Physics in OO game programming

So I am in the process of trying to learn how to develop 2D games.

I am playing around with both Android and C#.

The issue that I am having is this.

It is easy enough to draw a sprite of some sort. Where I struggle is to visualize how one can code interactions of various objects on screen.

For example lets say I have the following Object.

public class MyGenericObject {
    public MyGenericObject() {}
    public Int32 Width { get; set; }
    public Int32 Height { get; set; }
    public Int32 X { get; set; }
    public Int32 Y { get; set; }
    public Image ObjectImage { get; set; }
}

Lets say I want to model the behavior of an interaction between N number of these Objects. What is a typical pattern one would utilize in such a scenario?

So for example would you simply call a method such as MyPhysicsSim.DoPhysics(List<MyGenericObjects>);

Assuming this is not a huge stretch. Inside of this method then, how do you calculate the interactions and resulting movements? I just can't get my head around it (Obviously I do understand that there are basic equations that can solve direction and speed and so forth but I just can't seem to work out how to apply these as an algorithm).

I have looked at numerous tutorials and all of them seem to concentrate on just drawing an object or assume a level of understanding about the internals that is way over my head. So I am hoping for a really simple, dumbed down response.

So basically what I am asking is how do you approach interactions between 2D objects in a OO paradigm for dummies?

Upvotes: 2

Views: 596

Answers (1)

yan
yan

Reputation: 20982

Traditionally, most games have a loop similar to the one below somewhere at the core:

while (1) {
    World.respondToInput();
    World.updatePhysics();
    World.renderScene();
    Timer.waitUntilFrameExpires();
}

and the 'updatePhysics()' method can do something very basic, such as:

for (Object obj1 in World.trackedObjects()) {
    for (Object obj2 in World.trackedObjects()) {
        if (obj1.influences(obj2)) {
            obj1.update(); obj2.update();
        }
    }
}

So you basically have a 'tick' in the world you're simulating, and your code works to reflect the delta in the scene that would have occurred.

Upvotes: 6

Related Questions