Tuesday, May 03, 2016

Predicting Physics

Say you're playing a game of football with Sandra Bullock. Sandra is running in some arbitrary direction, so you will want to throw the ball somewhere in front of where she is at the time of your throw. In addition to this, since gravity exists, you will also want to throw the ball upwards a bit. We intuitively understand these concepts, and carry out basic, inexact predictions like this all the time.

Similarly, if you wanted to beam yourself from a planet onto a starship moving at warp speeds, I would imagine there would be a lot of physics predictions to take into account. Luckily, only rarely in games do we need to take relativity into account when predicting physics.

Predicting an object's physics is as easy as running your object's integrator (update) functions a bunch of times, without applying those new positions. If you have a fixed framerate, passing that fixed framerate into your special prediction integrator as its delta time will return a highly accurate prediction.

In my asteroid physics prediction demo, the first thing that had to be done was to calculate a time value. How far in the future should we predict? I derived that time value based off of the distance of the mouse cursor to the missile silo. This asked and answered the question of: "How much time will have passed given the missile's initial position at the silo (P1), the missile's final position (the mouse position, P2), and the linear speed of the missile?" A simple calculation:
t = distance between P1 and P2 / missile speed

 Given this time variable, solving for the final position of the asteroid was now possible. While the missile moved at a constant rate, the asteroid moved not only at a variable rate (acceleration), but a variable acceleration (jerk). Quite a complex calculation to do all in one go (I'm not sure if this is solvable using one equation). Luckily, computers are great at repetitive tasks!

So, in a for loop: 
for (float i = 0.0f; i < TOTAL_TIME; i += FIXED_TIME_STEP)

I integrated i times, and saved off the final position after simulating real-time physics in one frame.
Pretty simple! This was so interesting to work with, however, because the asteroids moved with variable vector accelerations defined by a gravitational force. The asteroid relied on only two variables to move: an initial speed and the force of gravity. Below is the derivation I used to go from this gravitational force to a manageable vector acceleration (which was then simply added to the velocity).

And that was it! A cool thing about predicting physics is it has nothing to do with the accuracy of your game's physics: no matter what kind of integrator function (real or imaginary) is implemented, predicting this physics is as easy as running a special version of the integrator for any given time.

No comments:

Post a Comment