Previous Section  < Day Day Up >  Next Section

Speed and Velocity

Any time an object is moving, it has some speed. Speed measures how fast an object is moving. If an object has speed, it also has a velocity, which is simply the vector version of speed. You might want to flip back to Chapter 4, "Vector Operations," for a quick refresher on the difference between a vector and a scalar quantity. Velocity is speed with a direction. In one dimension, the direction is given by positive or negative. (Chapter 10, "Motion in Two and Three Dimensions," address how to deal with direction in 2D and 3D.) For now, just consider the motion of an object along a straight line, where positive velocity is forward and negative velocity is backward.

NOTE

The terms "speed" and "velocity" may be used interchangeably in dialogue. Whenever speed is used, the direction is ignored.


Let's first look at an object moving with a constant velocity. For example, suppose I set the cruise control on my car to 60mi/hr. If I maintain that constant speed for an hour, I should go 60 miles. If I keep the cruise control set, I should go 120 miles in 2 hours, 180 miles in 3 hours, and so forth. This leads to the following statement.

Displacement with Constant Velocity

displacement = velocity * time (D = v * t)

for any constant velocity v.


NOTE

If you chose to ignore direction because the road is not perfectly straight, the same formula applies to the scalar equivalents: distance = speed * time for any constant speed.


Example 8.1: Finding Displacement with Constant Velocity

Suppose you're programming a portion of a game in which the main character jumps into a vehicle with a constant velocity of 150px/s. How far has he moved after 1 second, 2 seconds, and 3 seconds?

Solution
  1. Set up a formula to calculate displacement:

    D = v * t = (150px/s) * t

  2. Plug in each time interval:

    After 1s: D = (150px/s) * t = (150px/s) * (1s) = 150px

    After 2s: D = (150px/s) * t = (150px/s) * (2s) = 300px

    After 3s: D = (150px/s) * t = (150px/s) * (3s) = 450px

Let's put this in programming terms. As I flip through my game frame by frame, I want to know how far my car moves between each frame. Remember that displacement is the change in position: new position, old position. If I plug that into the preceding formula, I get an equation that can go directly in the code:


//Passing through floats for velocity and time we return the resulting displacement.

float calcDisplacement(float vel, float time)

     {

       return vel*time;

     }

Some game architectures try only to pass the relative change in an object's position over a network to reduce the overall size and amount of network data. This results in sending a net displacement of the object as opposed to the raw firing of the absolute position of an object in the game. Using this method, it is possible to calculate the displacement locally and then fire off a change to the server only if needed. Try to expand this example to work with multiple time periods and calculate an object's total displacement over a larger measure of time.

Displacement Between Frames

New_position = Old_position + Velocity * Time

where Time is one frame (usually 1/30th of a second).


NOTE

The framerate will most likely not stay constant at 30fps. Most developers calculate a "delta time" by subtracting the system clock's value at the last frame simulation from the value at this simulation and then use that as the time factor. This way, the simulations aren't thrown out of whack by the changes in framerate that naturally occur when new AIs are spawned or particle systems are introduced.


Example 8.2: Finding a New Position with Constant Velocity

Let's revisit Example 8.1. You really don't care how far the vehicle has moved after 1 whole second. What you really want to know is how far it moves between frames (assuming that the frame rate is 30fps). If the vehicle is at the 50-pixel mark in one frame, where should it be in the next frame?

Solution
  1. Set up a formula to calculate the new position:

    New_position = Old_position + Velocity * Time = 50px + (150px/s) * Time

  2. Because the frame rate is 30fps, the time interval of one frame is 1/30th of a second. Calculate the new position with a time of 1/30th of a second:

    New_position = 50px + (150px/s) * (1/30s) = 55px

Creating a function to handle this calculation works like this:


//Passing through floats for velocity and time we return the resulting

//position at the time specified.



float calcPosition(float oldPosition, float vel, float time)

     {

       return oldPosition + (vel*time);

     }

All this works if you know the object is moving at a constant velocity. But how often do you drive around with the cruise control on? Certainly in some games, it's easy to set up sections in which a vehicle moves at a constant speed, but you probably wouldn't want to do this for a racing game. Next time you're in a car, watch the speedometer for a while; you'll probably notice that the speed constantly changes. Therefore, we need to discuss two different types of velocity: average and instantaneous. Let's look at average velocity first.

Suppose you take a road trip. You clock your miles using the odometer and find that you travel 200 miles in 4 hours. You might say that your average speed for the trip is 200 miles/4 hours, or 50mi/hr. However, you probably didn't maintain a constant speed of 50mi/hr (unless you had the cruise control on). Most likely you sped up at different times or even came to a stop for a red light, so your speed probably kept changing during the trip, but the average speed was 50mi/hr. The line over the v indicates that we're using the average velocity, as shown next.

Average Velocity

graphics/08equ01.gif


for any displacement Dx and time interval t.


Example 8.3: Calculating Average Velocity

Suppose a police officer sets up a speed trap on a straight section of a busy road. He marks a ¼-mile section on the road, as shown in Figure 8.1. Using a very accurate stopwatch, he times 8 seconds from the instant you cross the first line to the instant you cross the second line. If you're driving in a 60mph zone, will you get a ticket?

Figure 8.1. A speed trap.

graphics/08fig01.gif

Solution
  1. Set up a formula to calculate the average velocity:

    graphics/08equ02.gif


  2. The average speed of 0.03125mi/s is probably meaningless to you, so convert that to mi/hr. (You might want to flip back to Chapter 7, "Unit Conversions," for a review of unit conversions.)

    graphics/08equ03.gif


    You'd probably get a ticket!

Instantaneous velocity is somewhat different in concept. As you drive down the road, your speed (or velocity) keeps changing. At any moment you can look at your speedometer and see exactly how fast you're going at that instant. Of course, an instant later, it's probably something different, but whatever the speedometer shows is your instantaneous velocity at that moment in time. We'll look at how to calculate instantaneous velocity in the next section, so for now just focus on the concept. I could be driving on the interstate and average 60mi/hr for the whole trip, but the police officer that clocked me going 90mi/hr doesn't care about my average speed. All he cares about is how fast I was going the instant he clocked me. That's the difference between average velocity and instantaneous velocity.

If you're traveling at a constant velocity, the average velocity is the same as the instantaneous velocity at any point.

However, if your speed changes at all, the average will probably be different from the instantaneous at most times. Here's the good news for game programmers. Most games are approached on a frame-by-frame basis, and most programmers shoot for a frame rate of 30fps. This means that if you take an average velocity between two frames, the time interval is only 1/30th of a second, which is pretty darn close to an instant in time, so you can treat that as an instantaneous velocity.

Example 8.4: Average Velocity Between Frames

Suppose an object in your game is at the 50-pixel mark in one frame. In the next frame, it's positioned at the 52-pixel mark. What is its instantaneous velocity in that frame, assuming 30fps?

Solution
  1. Set up a formula to calculate the average velocity between the two frames:

    graphics/08equ04.gif


  2. Because the time interval is so close to an instant in time (1/30th of a second), you can use it as a good approximation of the instantaneous velocity in that frame.

The code to handle this is also pretty straightforward. The start and end values specified here could be pixels or an absolute coordinate system. The solution works on the changes between the values over time so units don't matter as long as they are consistent. Apply any needed conversion in advance of calculating the average velocity.


float calcAvgVel(float start,float end, float time)

     {

       return (end - start)/ time;

     }

Velocity is one of the most important concepts in physics for game programming, because it controls how objects move. Remember that if all you care about is how fast an object is moving, just use the magnitude of the velocity vector, which is speed.

However, if you're trying to guide the motion of an object on the screen, always use velocity so that the computer knows in which direction the object is going. Also, as a programmer you should always be looking for simpler, faster ways to move things around. If you can use a constant velocity, the math is very simple. However, if you want more-realistic motion, you probably want the speed to constantly change. In this case, you must be careful and always use the instantaneous velocity rather than the average velocity over a longer time interval. We will revisit this concept in more detail in the next chapter.

Self-Assessment

1.

You're on a straight highway, and you decide to set the cruise control at 65mi/hr. After 15 minutes, how far have you gone?

2.

Suppose you're programming a moving platform for the player to jump on. The platform can move only left (–) and right (+). The platform is moving at a constant velocity of –5px/s. If it's currently at the 200-pixel mark, where should it be 3 seconds later (assuming that it hasn't reached the point where it turns around)?

3.

Suppose your character runs 25 meters in 20 seconds. What's his average speed for that 20-second time interval?

4.

Suppose the player in question 3 realizes he forgot something, so he turns the character around and runs back to where he started. What's his average velocity for the entire run?

5.

Suppose an object in your game is at the 300-pixel mark in one frame. In the next frame, it's positioned at the 295-pixel mark. What is its instantaneous velocity in that frame, assuming 30fps?


    Previous Section  < Day Day Up >  Next Section