A workable structure for physics?

Started by
12 comments, last by MrTwiggy 13 years ago

Note: I realize after writing thing, it is quite long. And I tend to ramble at some parts, so sorry for that.


Hey, there! First off, I wasn't sure whether this should be in 'Math and Physics' or 'For Beginners'. Because, I am a beginner and this is sort of a beginner question, but it's related closely to physics and math. If this isn't the right area, please feel free to move it, and I apologize.

Anywho, onto the situation. I'm a student in currently finishing my 11th year of Highschool. I've taken one introductory course into CS (c++) and have quite a bit of my own time learning about programming in general, and focusing mainly on C# and the XNA framework, which is a great starting point IMO. I'm part of a team that makes Indie Games for the Xbox 360, but I work with a more experienced programmer who helps me, and oversees my work. I'm planning on attending university (Carleton University to be exact, but it's not really well-known, and it's in Canada. So you probably haven't heard of it :P ) and getting my Honours degree in Computer Science, with a specialization in Game Development (Which I was careful to be sure it wasn't some flimsy degree centered on game design just to make easy cash from prey.) Although, I'm beginning to realize I am off course. Anyways, I'm currently in my first course of Physics, so my knowledge on the subject is fairly limited. I have a basic understanding forces and Newton's three laws.

I understand normal forces, free-body diagrams, the effects and force of gravity, net-force, friction (Static and kinetic) and velocity-related stuff. I realize that likely seems like very little to most of you, especially those who have minored or majored in physics already. But, that's what I have to work with. I was hoping to get some basic knowledge of how I can implent fairly standard and basic physics into games that I would be creating (likely with the XNA framework). The only problem is, I'm not sure how to structure everything. I mean, I COULD go out there and find some sort of physics engine, but those are typically extremely complex and long, and do far more than I need it to. And since I'm so relatively new to programming, I have a hard time reading, understanding and grasping other peoples' concepts and ideas for programming and their code. So I want to do my own. It wouldn't have much, it would not have particle systems and squishy stuff or whatever, xD. Just mainly a collision detection system, with friction, gravity, and all that stuff for players to move and collide with the world and objects.

I realize that I could probably do this with 'magic', which I have done before. But it's typically VERY bug-prone, and it just doesn't feel right. So I've decided to try and build a system that implements atleast semi-realistic physics in terms of forces, gravity and opposing motion (walls and the such). However, I'm not really sure how to implement those things into code.

I sort of have an idea for the end result of movement. I could have a net-force object on the player, for example, that is an object of a seperate class, that holds it's scalar force in Newtons, and it's direction in degrees or something, which would have it's own function to translate that into a vector quantity that can be added to the player's position that roughly translates into that net-force of movement. However, the trouble I am having understand, is how to use collision detection and force-transferrence. Stuff like, applying gravity to the players net-force, using collision detection and normal forces that oppose force of gravity and whatever else.

Upon further thinking, I suppose perhaps I could do something like this. I would have the player's net-force object. Then when I detect a collision between, say, the floor, I would calculate the force of gravity (perhaps with a method in the player class that returns the force of gravity) and then have a function in the floor object that determines the normal force and adds it to the players net-force? I'm not really sure, and I'm sort of lost. Maybe I'm over my head, and should stick to magic until I'm done atleast my first semester of physics. Or if anyone has any other suggestions or ideas, I'd love to hear it.

Anywho, thanks for reading all of this, if you did. I appreciate any comments or feedback that are constructive in some way.

-Ty
Advertisement
Sounds like you've got the basis, Ty.

Here's some general comments and observations:

Some time ago, I wrote a pretty basic collision/physics engine, force-based as you describe. That approach handles multiple collisions for a single object nicely. I maintained just about everything in vectors. I.e., I'm not sure I see a need to divorce the scalar force from it's direction. Maintaining it as a vector permits adding collision forces directly, translating forces at a point away from the center of mass to a torque vector about the center of mass and a force through the center of mass, etc.

My approach to collision detection was, similar to ODE's approach (Open Dynamics Engine), to assign to each body one or more primitives - spheres, planes*, boxes and rays. I wrote ( and copied from several sources ) routines for most pairs of collision types (sphere-sphere, sphere-plane, ray-box, etc.). Ray-casting is a valuable addition for collision engines to be used in games.

*I allow for a "bounded" plane - i.e., a triangle, since that's a common structure for 3D meshes over on the rendering side of the app.

The physics portion of the engine simply implemented the equations of motion (Newtonian stuff).

I use that collision/physics engine in a game loop. Characters are given several sphere objects (head, chest, hips, legs). Static objects are assigned collision primitives as appropriate - the "scene" is primarily bounded planes (cleverly disguised as triangles), doors are boxes, etc.

At the beginning of the loop, the force (and optionally torque) on each primitive is zero'd out (if static = doesn't move) or set to a gravity force vector (if a dynamic object). Each dynamic object (an object that can move) is tested against all other objects for collision. There's a lot of spatial culling in that process (octrees and bounding boxes). The collision routines I wrote generate a separate data structure for each collision - references to the two objects, collision position, normal to the position, and depth of penetration. Those structures are pushed into an array of collisions for this time through the loop.

Then each of those collisions is examined and appropriate vector force(s) added to the object's total force vector. I use a force along the collision normal proportional** to the depth of penetration. I think of "penetrating" or "overlapping" objects as being compressed by the collision.

**Alternately, calculate the force using some material properties of the objects. You can make them rigid (large force per unit of penetration) or spongey (smaller force).

In the physics phase, given the total force vector on an object and a time dT since the last time through the loop, I apply the equations of motion - A = F/M, V = V0 + A*dT, X = X0 + V0*dT + 1/2*A*dT*dT, etc., to determine the object's new position (and orientation if you use torque). If you want to get fancy, because not all collision forces are directed through the center of mass, convert each collision force to a torque and a force through the center of mass.

For extra credit, calculate the tangential force due to friction for each collision and convert that to a torque and force. Maintain each dynamic object's angular as well as linear velocity. Take into account the object's shape and use the appropriate moment of inertia about the torque axis when applying the torque.

Just some ideas to play around with.

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.


I sort of have an idea for the end result of movement. I could have a net-force object on the player, for example, that is an object of a seperate class, that holds it's scalar force in Newtons, and it's direction in degrees or something, which would have it's own function to translate that into a vector quantity that can be added to the player's position that roughly translates into that net-force of movement. However, the trouble I am having understand, is how to use collision detection and force-transferrence. Stuff like, applying gravity to the players net-force, using collision detection and normal forces that oppose force of gravity and whatever else.

Force is a vector, why would you want to store it as a scalar?

If you were thinking of writing your own physics engine I would highly recommend you not to. There are libraries freely available, why not use one of those?
[/quote]
If you were thinking of writing your own physics engine I would highly recommend you not to. There are libraries freely available, why not use one of those?
[/quote]

Or, better yet, use several.
http://www.adrianboeing.com/pal/index.html

The great thing about physics simulation is that concepts like force & mass & velocity are universal to all simulation methods, so you can replace the actual simulation engine whenever you like, and usually expect similar or identical results.

Even if you're determined to write your own (which isn't a bad idea - it's just a lot of work, including literally reinventing the wheel), it would pay to be able to switch engines now & then, just to verify that your results are similar to everyone else's results.
The response of a mouth-breather:

Vector physics are simple (game physics) or complex (simulator physics). You are entering an understanding above and beyond mine; actually studying the reality of the world, yet you are still learning, and as such, I would recommend you start with a simple collision detection/force-transfer engine. Assume all objects are rigid and there is no friction (space, mate! Vacuum FTW!). Sounds smart as hell from me, but to you, I'm probably talking about bananas and pissing into my own mouth. What I mean is simple; programming physics is not about replicating the real world...

gasp WHAT?!

I know. Crazy.

Replicating the actual world requires an insane amount of cycles. You cannot create a simulator of reality on any desktop machine. There are just too many variables. The trick is to simulate reality by using things that...ahem look right. Heh.

'Look right' and 'are right' aren't always the same thing, especially inside computer memory.

How do I know this isn't bullsh*t? It's simple...My father is a PhD in Quantum Mechanics. So...If I want the actual expression for a problem, I need only ask. However...Reality doesn't translate to the screen too well. There are just too many variables.

What's the answer...?

Like I said: Looks real.

KISS, brother. Keep It Simple, Stupid. It'll be complicated enough to keep your mind engaged for a long time to come. Actual representation of physics inside an engine is the province of Post-Docs and Genius. You might be one...But not yet, mate. You'll find it challenging enough to program simple BoundingSphere collision at first. Work on simple representation of light; Ambient, Diffuse, Specular. Vertex collision, material force, material/air friction, viscosity, gravitational force, is...later :)

Have fun with Vector/Velocity/Mass calculations. Just remember...It's not 'real' if your frames per second drop below the screen's refresh rate :)


Oh...If I don't make any sense, or sound like a moron...It's because I am. I graduated High School (barely) and stopped. So...Take my words as you will... Hmm...What's the expression for Mass & Volume? heh. Have fun with programming, brother, just don't get too tied up in what is real as opposed to what looks real.

Keelah Sel'ai.
Thanks everyone for your replies! Although, my goal right now isn't really to create a full-fledged physics engine or system, it's mainly to have a force based transferrence. So like SeanH said, something with just rigid objects and force-transferrence. I really appreciate all of the replies, and I will definitely be able to use some of it :)


[quote name='MrTwiggy' timestamp='1302054144' post='4794851']
I sort of have an idea for the end result of movement. I could have a net-force object on the player, for example, that is an object of a seperate class, that holds it's scalar force in Newtons, and it's direction in degrees or something, which would have it's own function to translate that into a vector quantity that can be added to the player's position that roughly translates into that net-force of movement. However, the trouble I am having understand, is how to use collision detection and force-transferrence. Stuff like, applying gravity to the players net-force, using collision detection and normal forces that oppose force of gravity and whatever else.

Force is a vector, why would you want to store it as a scalar?

If you were thinking of writing your own physics engine I would highly recommend you not to. There are libraries freely available, why not use one of those?
[/quote]

Well, the way that I've learned it in class (which might be wrong?) is that a force can be represented like this: 220N[E30N] or something like that. So I decided for the sake of accuracy and simplicity, which might sound likes it more complex, but I figured it's a lot easier to just see 220N [E30N] than seeing a Vector2 quantity of (20, -8). So I thought that having a method inside of the net-force object that translates that automatically into a Vector quantity might be easier to manage? I'm not sure.

Also, I wasn't really thinking about writing my own full fledged engine. I have no idea was rays, ambiance, torque, soft-body (I assume like rubber?) and all that other stuff is. The only physics that I actually know or have learned yet is the basic rigid-body physics with force transference and net-force. Also, I'm not really creating it for practicality (but I will use it), but mainly for educational purposes. I think it would help me with my understanding of the basic physics, learn more about force-transference in coding and how to implement it, and become useful in the future, as I hope to start a 2D-Platformer soon (Mario clone anyone?).

Thanks again,

-Ty


EDIT: Also, I just remembered some stuff and came up with an idea. Newtons are forces, and refer to acceleration more than velocity right? I mean, if you apply a 1000N force to a 1kg object for a split second, it won't automatically go to 1000m/s, but it will accelerate at a rate of 1000m/s^2. So perhaps, as an example, I would have a player, and I would have TWO objects inside of it. A net-force object, and a Vector object called Velocity. This Velocity would be added to the players collision at the very end of every update loop (and it would be multiplied by the ElapsedTime in seconds between frames, so that everything maintains a per second basis). Right before the end of the update loop, before you add the velocity to the players position, I would run a method in the Net-Force object that translates the total force into an acceleration amount for that frame, and add it to the velocity. So once that's done, all I need to do is before the end of the update loop when it does that, I can just add and subtract forces and such to the player's netforce. I mean, in theory, that sounds correct. But there could be a gaping hole in it? Any thoughts?

Well, the way that I've learned it in class (which might be wrong?) is that a force can be represented like this: 220N[E30N] or something like that. So I decided for the sake of accuracy and simplicity, which might sound likes it more complex, but I figured it's a lot easier to just see 220N [E30N] than seeing a Vector2 quantity of (20, -8). So I thought that having a method inside of the net-force object that translates that automatically into a Vector quantity might be easier to manage? I'm not sure.


Well easiness of interpretation depends on what you're familiar with, but some representations are easier to work with, in the sense of programming once you're familiar with them. It'll be easier to debug as well, part of debugging is noticing abnormalities, which gets easier once you get a 'feel' for the numbers or in this case vectors.


EDIT: Also, I just remembered some stuff and came up with an idea. Newtons are forces, and refer to acceleration more than velocity right? I mean, if you apply a 1000N force to a 1kg object for a split second, it won't automatically go to 1000m/s, but it will accelerate at a rate of 1000m/s^2. So perhaps, as an example, I would have a player, and I would have TWO objects inside of it. A net-force object, and a Vector object called Velocity. This Velocity would be added to the players collision at the very end of every update loop (and it would be multiplied by the ElapsedTime in seconds between frames, so that everything maintains a per second basis). Right before the end of the update loop, before you add the velocity to the players position, I would run a method in the Net-Force object that translates the total force into an acceleration amount for that frame, and add it to the velocity. So once that's done, all I need to do is before the end of the update loop when it does that, I can just add and subtract forces and such to the player's netforce. I mean, in theory, that sounds correct. But there could be a gaping hole in it? Any thoughts?


Force acts on acceleration -> acceleration acts on velocity -> velocity acts on position, so you'll have to store a little more than just force and velocity. Other than that, I think you're on the right track.
Acceleration is based on Time, so you'll want to store your object's maximum speed. If you store it's maximum speed, you'll be able to have objects that move at different speeds. If you don't, you'll need to setup a global constant that you can use for all the objects in your world.

So, you'll need to find the elapsed time (usually in milliseconds, if you're using VisualBasic or one of the other .NET platforms, you can look for the StopWatch object to help you with that), once you have the elapsed time, you'll be able to figure the object's current velocity (for the current frame) by calculating the elapsed * the Acceleration (Max Speed).

Velocity = Acceleration * Elapsed / 1000

I'd stick with constant accelerations or you'll find the formula for velocity gets...hairy.

What this doesn't consider is the mass of the object, so once you're comfortable with Acceleration in a frictionless, massless world, try adding mass to the object. It'll look something like:

Velocity = (Acceleration * Elapsed / 100) / Mass

...I think. heh. Getting a bit beyond my brain here. Looks about right to me (though I've not tested it), the heavier the object, the longer it takes to reach maximum acceleration.

Anyway, after that, you could start considering friction (such as an underwater world), gravitational forces on your object's trajectory and then you can mess with acceleration modification by gravitational forces which would be something along the lines of the dot product between the Gravity's Normal (pull direction) and the normalized Trajectory modified by the distance from the object (gravity falls off as you get farther away).

Actually figuring out the fall off for gravitational force in conjunction with distance is way beyond me, but you could use a simple formula to make it look right without actually getting everything actually right. Anyway, it'd probably be a function of the Total Force divided by the distance from source although I think in reality it as a strange curve when viewed on a graph. Use a linear (simple division of total force and distance) to represent it at first, once you're comfortable with it, you can start working on generating an algorithm that is representative of gravity's actual laws (which by that time, if you haven't learned the expressions for the laws, you'll need to look it up on a physics website and convert the expression to an algorithm on your own, though you will likely be able to find someone to give you a hand, that's way beyond me).

Acceleration is based on Time, so you'll want to store your object's maximum speed. If you store it's maximum speed, you'll be able to have objects that move at different speeds. If you don't, you'll need to setup a global constant that you can use for all the objects in your world.


If you don't know how game physics is usually done, should you really be giving advice on it? If you limit objects' speeds like that, then a player with a top speed of 10km/h riding a train with a top speed of 100km/h would be dragged through the back of the train as it accelerates. Nobody likes getting dragged through a train.

The better way to give objects different speeds is by giving them appropriate masses, appropriate forces to move them around, and appropriate forces to resist their movement. It's not that hard to do, and it will make any game more fun (and nicer to look at) than just guessing at how objects might move. Even super-simple Newtonian physics with boxes & Euler integrators will work, like it worked in Super Mario Bros. and every decent platformer ever since.

If you were to fake your physics naively instead, your game will stop being fun as soon as players encounter unexpected weirdness like not being able to ride a train, or encountering a "strange curve" for planetary gravity that throws them straight into the sun.


MrTwiggy - you were probably taught that forces can be represented in non-vectory ways because your teacher was accustomed to doing physics with a pencil & paper. On a computer, it's far more useful & efficient to think in vectors. Basically they just encapsulate X-position & Y-position together (and the same for velocities & forces), but no matter how fancy you want to get with your physics, vectors will always be faster & friendlier than things like compass headings or top speeds.
When you are controlling player movement, I'm assuming you add a force to the player, correct? Which causes an increase in acceleration, and thus an increase in velocity and position. However, how do I limit the input force, but not the external forces? (Such as riding a train) Because, in these games, the players accelerate, and then they reach a maximum speed. But how do I enable that effectively for the input speed?

EDIT: Also, does anyone know any good tutorials or guides that go in-depth with a 2D rigid body dynamics physics engine? I have found some, but they are almost all in C++, and the inner-working of C++ seem to complicate everything even further. So hopefully something that is either not language specific, or is C# or XNA specific. Thanks.

This topic is closed to new replies.

Advertisement