Slashdot Mirror


Physics For Game Developers

Richard Jones writes: "In my opinion, the most difficult aspect of writing a good 3D game is coding complex physics. If you can take away all the flashy graphics, texture maps, light and shadows from a game, and it's still at least 75% as playable and addictive, then you have an excellent game. But too many programmers seem to be ready to concentrate on the graphics, neglecting the underlying physics which make the game playable. If you compare, say, Re-volt with its fabulously detailed models of remote-controlled cars, and Carmageddon which on the N64 at least has sucky physics, well I know which one I'm still playing." He's contributed his review (below) of a book intended to help game programmers make games that aren't sucky. Physics For Game Developers author David M. Bourg pages 326 publisher O'Reilly rating 8 reviewer Richard Jones ISBN 0-596-00006-5 summary A good introduction to the difficult subject of writing 3D games and simulations with accurate physics, let down by a few minor snags.

Programmers who want to get serious about game physics will love David M. Bourg's Physics for Game Developers. As I've said, the subject is inherently very difficult, and the book assumes that you are already familiar with vector and matrix arithmetic up to college level, integration and differentiation, and at least you hazily recall your mechanics/physics lessons from school. You also won't be afraid to wade through Bourg's carefully documented derivations of formulae for various physical effects, and his well-commented source code.

The book starts off by recapping the basic concepts of mass, centre of gravity, moment of inertia and inertia tensors. Bourg assumes that you have a working grasp of these subjects, and I admit that I had to go back to some of my A-level mechanics text books. He then goes straight into kinematics, where he uses standard (but forgotten!) integration techniques to calculate velocities from accelerations and positions from velocities. His examples are excellent, although a few exercises wouldn't have gone amiss. The chapter on forces covers a great many different types of forces such as springs and buoyancy, but curiously omits the important subject of contact forces (the normal force that a table, for instance, exerts on your computer monitor to stop it falling through the floor). In fact contact forces don't appear until much later in the book. Particles, rigid bodies and impulses (forces from collisions) are introduced in chapters 4 and 5.

At this point I have to say I was a little bit confused. What did this have to do with game programming? Everyone knows that games spend most of their time running round a single big "main loop," working out the forces on each object, looking for collisions and working out which keys the user is pressing. It doesn't seem imaginable that a game programmer could completely solve all the equations of motion by pure integration at the beginning of the game, and then just run the positions of the players through the graphics engine like a movie!

I already knew a little about this from what I'd found from the web, but what most games actually do is calculate all the forces on all the objects (players, scenery, etc.) in the game, and then integrate them at each step. Some of these forces will be generated by human players pressing keys on the keyboard or wiggling the joystick, and that's how the objects end up moving. Pure integration isn't usually possible, so the physics engine performs numerical integration - a kind of fast approximation to the pure "closed form" solution. Numerical integration is itself a tricky subject, but it's the meat-and-veg of good game programming. Surprisingly, numerical integration and a realistic main loop doesn't appear until chapter 11 (172 pages into the book). I skipped straight to this section, and I suggest you do so too...

The chapter on numerical integration is excellent and contains the first realistic gaming (or at least simulation) code. Many games I've examined use simple numerical integration, like this:

// At each step ... A = acceleration, dt = time step
Vx += Ax * dt;
Vy += Ay * dt;
Sx += Vx * dt;
Sy += Vy * dt;

Unfortunately this method (Euler's method) is very inaccurate and unstable: if you tried to simulate planets orbiting around a sun using this method, they'd soon fly off into outer space unrealistically. Bourg gives an excellent introduction to better methods such as the "improved Euler" method and the popular Runge-Kutta method, and he covers them in a context which will make it clear how to use these methods in your own programs.

The book reaches a crescendo with three fully developed simulations: two hovercraft which you can drive around and jolt into each other like bumper cars -- they spin around realistically; a flight simulator; and a 3D car which can be crashed into blocks that bounce around. Again the source code is meticulously commented and generally well written. My only two reservations about the code are: It would be nice if Bourg had chosen to use OpenGL instead of Direct3D so that those of us without regular access to Windows could actually compile and run the examples. The book would make an ideal companion to the OpenGL Red Book. And coming firmly from the Windows camp, Bourg's examples are full of all the horrors of Win32 APIs and Hungarian Notation. But maybe that's just my personal preference :-)

So in summary: The Bad Points:

  • Measurement systems: Bourg moves uneasily between the English/US system and the European SI units. So we get examples which combine ft/s, meters, slugs and kilograms, uneasily converting between the two. He should have chosen one system and stuck with it.
  • A common complaint about computer books: I've just spent 25 quid on a book which will sit open on my desk for months. Is it too much to ask that it be ring bound?
  • Some subjects are not explained in enough depth. Particularly: moments, contact forces, impulse methods. Bourg should probably have written a chapter or three on collision detection.
  • The chapters are presented in a very strange order. Move chapters 6-10 until later, or introduce numerical integration earlier.
  • A few of the illustrations are inaccurate.

and The Good Points:

  • Considerably better than the usual round of maths/physics text books which make up this field. In fact, this is really one of only about 2 or 3 significant books in this area which are pitched for game developers as opposed to mathematicians, and it's certainly the best.
  • The areas which are covered are done well, in significant depth, with a good bibliography where you can find out more.
  • The commentary on the difficult equations is good, and Bourg resists the temptation to derive many of the formulae he presents, instead referring interested readers to other references.
  • Code is well documented and explained.

And now I suppose I have no excuse not to resurrect XRacer :-)

You can purchase Physics for Game Developers at Fatbrain

25 of 328 comments (clear)

  1. Baldur's Gate for PS2 by sam@caveman.org · · Score: 3, Interesting

    i've played a lot of games, and gone 'wow' at some of the eye candy, but if you've played baldur's gate for PS2 you know that the coolest thing that has ever been coded for a game is the WATER for this game. you leave a wake behind you when you walk through it, you splash when you jump in, and ripples interact and reflect from the shore. maybe the physics aren't 'perfect' or whatever, but the realism of the water was enough to really 'immerse' myself into the game.

    -sam

    --
    burn the computers. go back to the abacus.
  2. How about "extreme game programming"? by YouAreFatMan · · Score: 3, Insightful
    One idea might be to pair up a design-minded developer with a science-minded programmer. Kind of the right-brain/left-brain thing. Not that there isn't overlap, but usually someone is better at one than the other. And even if someone has both good design and scientific skills, it is hard to practice them at the same time. I know I have to take time to "switch" modes when going from creative stuff to more technical stuff.

    So pair up a couple of guys. One to worry about the artistic design, and another to worry about realistic physics.

    --
    Robotiq.com is heavily tested on animals
  3. Physics isn't everything by alen · · Score: 3, Insightful

    Some people aren't into super realistic physics. Some don't want to read a 300 page manual for a flight sim and spend weeks figuring out the flight model. They would rather just grab a joystick and start playing like in Wing Commander.

    1. Re:Physics isn't everything by arkanes · · Score: 4, Interesting

      The space sim Terminus is great in this regard - when you start the game, you can select the level of reality in your physics - anywhere from (almost) 0, to full Newtonian. So if you just wanna blow stuff up, go for 0, and if you want to have to worry about carefully calculating your path so you take maximum advantage of gravity and don't waste fuel on course adjustments, you take full. Great stuff. I reccomend the game, BTW, fantastic gameplay even if the graphics lack by todays standards.

  4. A better book to read for Game Physics... by FortKnox · · Score: 3, Insightful

    Its called "Physics for Scientists and Engineers".

    Lets face it, the best physics is REAL physics.

    If you want your game to have good physics, then slap a good physics engine (based on real formulae) into it!

    --
    Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
  5. i just bought this book online.... by Mr.+Quick · · Score: 3, Informative

    ..although i picked the cheapest form of delivery so it won't be here for a bit more time...

    i read thru the sample chapter [here] it's all about particle physics. i was quite impressive, i enjoy the *conversational* style that most o'reilly books have.

    i implemented all of the examples in java using java3d.

    i hope the book meets my expectations....

  6. more fun blowiung up stuff with accurate physics by thex23 · · Score: 3, Interesting
    Realistic physics? Yes, please!

    I want a FPS that lets you blow holes in walls, accurately representing physical damage from weapons. Imagine Counter-Strike with realistic bullet physics: ricochets, windage, and weapon recoil that isn't predefined.

    Hacking physics though, now that's a job and a half: figuring out a quick and dirty method of approximating the complexities of the real-world, and still have it look natural, making it look like a real environment filled with objects that have familiar properties and behaviours. And then blowing them up, REAL GOOD.

  7. Re:Don't need to be that exact by skoda · · Score: 5, Insightful

    There's a difference between "unrealistic" and "unstable".

    Unrealistic suggests that it doesn't behave as in the real world -- but that doesn't mean it isn't modeled on the same principles (acceleration, momentum, etc.) And you still want to simulate it consistently; it should "feel" right.

    But an unstable computation method can "blow up", regardless of realistic or unrealistic "physics."

    Consider:
    Jump pads in games like Quake or Unreal are "unrealistic". But they are modeled at least partially on physics. But to make them work right, in all their unrealistic glory, the computation method must be stable.

    If it wasn't stable, then you might something like:
    - Multiple, successive jumps on one would lead to a "blow up" where the player would be wildly, and unexpectedly shot through the roof and to the outer edge of the game universe.

    For both realistic and cartoon physics, you need accurate and stable computation methods.

  8. Games aren't about realistic physics by Captain_Frisk · · Score: 4, Redundant
    I've noticed alot of comments here about realistic physics in games.

    I remember reading an article with a game developer a while back, who pointed out that the key for physics in a game wasn't realism, but consistancy.

    He was developing a racing game, and says in order to make the game more fun, he had to sink the center of gravity for all of the cars several feet below the pavement, so that the cars wouldn't tip over when making hi speed turns.

    As long as all the cars behaved the same way, it didn't matter that you were "cheating".

    When playing your game, the user is entering your world, and learns a new set of rules. As long as you present your set of rules as consitant, it doesn't matter if they don't correspond with how things behave in "real" life.

    Captain_Frisk - wannabe game designer.

  9. Chris Hecker's Physics tutorials are FREE! by strags · · Score: 5, Informative

    http://www.d6.com/users/checker/dynamics.htm

    provides an excellent, and free alternative to purchasing a weighty tome on the subject. Chris covers the details of rigid body mechanics in a thorough, but light manner.

    I went to a physics lecture at GDC, the most memorable part of which was Chris saying:

    "Here's how it's going to go... you're going to write your first rigid body dynamics simulator. You're going to simulate a cube dropping onto a plane. You'll run the program, the cube will drop, hit the plane... and disappear."

    So, so true.

  10. Carmageddon by CaseyB · · Score: 3, Interesting
    Carmageddon which on the N64 at least has sucky physics,

    Excepting the possibility that the N64 version is completely different from the PC version, you are completely clueless. Carmageddon, of ALL the games you could have chosen, was a pioneer in game physics. It was the very first game that I played that had a real rigid-body simulator built into the engine.

    Say what you will about the gameplay, or the physical settings (gravity was too low), but you can't say it had sucky physics. The cars and environmental objects interacted in an incredibly realistic manner. It was miles ahead of Re-Volt in that department.

  11. Games vs. Simulations by dreadpiratemark · · Score: 5, Interesting

    I don't know that I really agree with the idea that physics need to be wildly realistic in the 'games' that I play. Honestly, I don't want to know what kind of recoil the rocket launcher in Half-Life would inflict on my character. I'm happier just watching the rocket track nice and straight towards my target instead of attempting to pick myself up off of the ground where I slid to a stop from the highly realistic recoil.

    On the other hand, when I play a 'simulation' the physics are quite important. The best physics I've found in a sim are in a 3-year-old game: Grand Prix Legends. You're racing 1967-era Formula One cars, which means skinny tires, no downforce, high powered...which is a combination for difficult driving. But the physics engine is spectacular: you touch the gas when in neutral, you can feel the torque twist the body of the car; each wheel has its own model; touch the gas a bit to hard in a corner and be prepared to swap ends of the car, etc., etc.

    The graphics are what you'd expect for a 3 year old game, but a dedicated community has sprung up to support the sim with everything from replay analysers, new tracks and graphics, and even a movie maker!

    It seems that if you make a sim with good enough physics behind it, the fans of it can create new 'eye candy' to keep the sim looking good. But if you have crappy gameplay (see: Andretti Racing) and good graphics, the game will quickly be relegated to the bargin bin when something prettier comes along.

    -Mark

  12. Who wants realistic physics? by Junta · · Score: 5, Insightful

    I'll bet that in at least 90% of the games out there realistic physics would completely ruin the whole fun. What is the point of interacting with a fake environment when the environment reacts the exact same way real life reacts? Racing games are a good example. People want cares to handle well, generally. They don't want realism, in real life operating cars at high speeds is a lot more difficult than most games.

    And in *any* game where people jump, realistic jumping becomes completely pointless. People want to be superhuman. Imagine quake with realistic physics....

    Realism is not the high mark of games in all aspects, that is the whole point of games, to escape reality...

    --
    XML is like violence. If it doesn't solve the problem, use more.
    1. Re:Who wants realistic physics? by RobertFisher · · Score: 3, Insightful

      This is a good point, and a valid one.

      It is true that in some games -- a combat flight simulator, for instance -- one design goal would be to achieve the most realistic physics possible. The average kid popping quarters into an arcade game isn't looking for realism, but some folks certainly will.

      However, I think the importance of _self-consistent_ physics is quite critical. You can invent your own set of "physical laws", which may be similar to those we are familiar with (ie, with moon gravity instead of Earth gravity) or completely and utterly different (ie, with Matrix-like time and space distortions or a Tolkien-like world replete with magic). However, the world you put forth should appear at once both plausible and self-consistent. Indeed, knowing real physics and the numerical methods to treat it would certainly help game programmers in their own constructions, if only by serving as an intricately balanced example which can serve as a launching point for their work.

      Bob

      --
      Science, like Nature, must also be tamed, with a view turned towards its preservation.
  13. Cartoon Physics by devnullkac · · Score: 5, Funny

    I'm still waiting for Physics for Cartoon Developers: just how long should a character remain suspended after realizing he's in mid-air? We'll need pure math computation methods for ordinary cartoons and numerical methods for interactive cartoon games.

    --
    What do you mean they cut the power? How can they cut the power, man? They're animals!
  14. Re:throw physics out the door... by Dimensio · · Score: 5, Interesting

    I think that the most glaring physics error commonly seen in many games -- especially platformers and FPSers -- is violations of inertia. Take almost any game where 1) your character can jump and 2) there are horizontally moving platforms of some sort. Stand on a moving platform and jump as it moves. In almost every single game you play your character will jump straight up in the air and the platform will move out from under the character, even though real physics should have the character continually moving in the direction of the vehicle (air resistance isn't that strong or your characters wouldn't be able to move at all).

    I think that I've seen one game (whose name escapes me atm) that actually got it more or less correct -- and I think that was just a game engine quirk that caused it.

  15. Runge-Kutte? Give me a break! by pclminion · · Score: 3, Informative
    First of all, let me say that I will be getting my degree in physics in a few months, and I'm well versed in physical simulation. Not in the game arena, but in the applications arena.

    Runge-Kutta is a complex method for quickly and accurately solving differential equations by numerical means. It is used instead of simple Euler iteration because it is equivalent in speed and gives much more accurate results. It works by adjusting the timestep dynamically to skip over regions where the system is changing slowly, and to integrate more carefully when the system is changing quickly.

    This is all well and good when you are trying to do something important, like simulating heat flow within in a heatsink. But for simulating the orbits of planets around a star, for example? What a waste of time! The orbit is elliptical, so just simulate a freaking ellipse!

    What about space missiles? Do you need Euler integration? No! There is a closed-form solution to the linear acceleration problem -- it's a quadratic. This procedure does not give low error. It gives zero error.

    I read this guy's articles several months ago. I thought he was off his rocker then, and I still think so now.

    1. Re:Runge-Kutte? Give me a break! by pclminion · · Score: 3, Insightful
      What do you mean by realistically? If you mean, for example, that the sun in your game solar system attracts the spacecraft, and if you wait long enough you'll unfortunately fall into the sun, then I'd say your game is a bit too realistic. The gravitational force on a spacecraft at any significant distance from a star extremely slight in comparison to the forces acting on the craft locally, such as thrust and collisions.

      Even if the gravitational force were extremely strong, it wouldn't make much difference in space battle. You still point the missile at the enemy and shoot it. You, the missile, and the enemy are all accelerating toward the sun at equal rates. The fact that a G-field is present makes absolutely no difference, since the field is uniform, at least when you are quite far from the sun and the spacecraft are relatively close to each other. In a fun game, the craft will not be far apart, since it's not much fun to fire on an an enemy when you can't see the pretty explosion.

      Look, I'm going on and on about a specific example, when my real point was much more general. "Realistic" behavior of objects can be very closely approximated with very simple methods. The player will not know the difference. Problems such as integrations "blowing up" can be easily avoided simply by looking for the blow-up and correcting for it.

    2. Re:Runge-Kutte? Give me a break! by mOdQuArK! · · Score: 3
      This is all well and good when you are trying to do something important, like simulating heat flow within in a heatsink. But for simulating the orbits of planets around a star, for example? What a waste of time! The orbit is elliptical, so just simulate a freaking ellipse!

      That's only true in a two-body system.

      What about space missiles? Do you need Euler integration? No! There is a closed-form solution to the linear acceleration problem -- it's a quadratic. This procedure does not give low error. It gives zero error.

      Only if you assume a flat earth with constant acceleration at all altitudes - which is an incorrect assumption when you're trying to model intercontinental ballistics.

      I read this guy's articles several months ago. I thought he was off his rocker then, and I still think so now.

      Apparently, your soon-to-be degree in physics doesn't imply a degree in common sense.

  16. Forgotten downforce? by Maddog+Batty · · Score: 3, Informative
    Sure the game developer may have found that changing the physics model made the game more fun to play but one possibility is that (s)he had forgotten to model downforce. An F1 car produces a downforce higher than its own weight (cue comment about F1 cars being able to drive on the ceiling). Without downforce, a car would flip going around a corner at F1 speeds.

    A very simple (*) way to model downforce is to drop the centre of gravity of the model so that it is below the ground. Other variables such as tire grip also have to be changed as well but these are generally constants.

    (*) Downforce changes with vehicle speed so this is a very simple model.

    --
    wot no sig
  17. Lara Croft by Stephen · · Score: 5, Funny

    Realistic physics in games will never catch on. Lara Croft would keep falling over forwards.

    --
    11.00100100001111110110101010001000100001011010001 1000010001101001100010011
  18. Why game physics is hard by Animats · · Score: 3, Informative
    I'll have to take a look at this new book, but from the description, it looks like the author doesn't address the hard problems. Alternatively, the reviewer may not know what to look for.

    As someone else pointed out, there's a straightforward way to approach game physics, based on what you learn in a first-year dynamics course, and it won't work. Free flight is easy. Contacts and collisions are hard.

    Detecting contacts between objects is complicated, but well-understood. There are several free collision-detection engines available, and many research papers. The time bounds are quite good; only slightly worse than O(N) with the better algorithms. Writing a collision detection system is a big job, but the theory is tractible.

    Taking appropriate action when you detect a contact is the hard part of the problem. Bouncing balls are easy. Multiple irregular objects with multiple contacts, slipping and sliding, are hard. Most current games simplify their collision geometry down to cubes or spheres and botch the hard cases ("But my sword went right through him and he didn't even notice!") The latest generation of games is just starting to get contact right. In another year, correct contact handling will be a "must-have" for commercial games.

    If you simulate contacts between objects with a spring and a damper, you run into numerical stiffness during integration. Soft objects at slow speeds will bounce fine. In a hard collision, the forces become huge for short periods. The simple integration algorithms will result in huge errors, and the objects will go flying off into space.

    If you simulate contacts between objects as impulses (an impulse is an infinite force applied for zero time, but with a finite energy transfer), two objects bouncing off each other will work great. More than one contact per object doesn't work too well. Resting contact doesn't work; objects may fall through each other. And everything bounces like it's a pool ball, because all collisions take zero time.

    If you try to do everything with constraints, resting contact works. But combinations of sliding and resting contact result in wierd corner cases that are hard to get right. Trying to solve contact, rather than simulate it, leads to static indeterminacy. (Think of a table with four legs, slightly different in length. How the table behaves is very sensitive to small changes in leg length. Numerical solutions of multipoint contact problems become similarly sensitive). This is the approach Baraff preaches at SIGGRAPH, but few others have been able to implement it.

    After a few years on the problem, I developed Falling Bodies, which successfully solves this problem well enough to simulate a human figure falling down a circular staircase. It can be done. I hammered through the spring-damper problem by using unusual and robust integration techniques. This is computationally expensive, but sound.

    If you're developing a commercial game, and need working physics, go with the Havok engine. They have a rigid body engine, a soft-body system, and a specialized vehicle simulation engine. (Yes, vehicle physics in games typically has fake components. In most racing games, the tires are impossibly good and the vehicle CG is impossibly low. But you need a real physics engine to fake it properly.) It's not cheap, but you're not going to solve this problem in a few months. Major developers have blown years on this problem and failed. Trespasser, from Dreamworks, went down the drain that way.

  19. Not inaccurarte and unstable by Junks+Jerzey · · Score: 3, Informative

    Unfortunately this method (Euler's method) is very inaccurate and unstable

    This is only true if you're simulating a standalone system (like the orbiting planet example). In real games, the player is constantly pressing the controller, collisions are occurring, and the "AI" is making decisions. Stepwise integration makes perfect sense in that case. Calling it "inaccurate and unstable" shows a lack of game development experience.

  20. Troll? by autopr0n · · Score: 3, Informative

    How is this a troll?

    Hrm. Seems my last five comments have each been modded down one point. Fortunetly for me, I could care less.

    --
    autopr0n is like, down and stuff.
  21. "real" physics?! by TopherC · · Score: 3, Insightful

    First, physics is inherently descriptive and approximate anyway, so if there is a "real" physics, it has yet to be discovered. Physicists are always working with approximations and numerical methods, but it's best to go as far as you can with "exact" solutions and generalities. Then, when you need to start doing numerical work, you have some place to start from. You can't do numerical integration unless you know what to integrate.

    Second, the usual 100-level undergrad textbook in physics tells you a lot of things that you probably don't need to know when designing games (like E&M and some quantum mechanics), but also leaves out the more practical aspects of classical mechanics when dealing with less-than-ideal objects. Once you work with the motion of objects that are not spherically symmetric, you need mechanics at the next level, and you need to work with matrices and vectors. This stuff isn't difficult, but it's not in the typical undergrad textbook. And it does require a bit of mathematics, like most things that are worthwhile.

    So it sounds to me like this book does have an important niche to fill, combining undergrad classical mechanics, a sampling of junior-level classical mechanics, and some numerical methods to boot.