Time Based Movement in D

We can use the Vector3 class to do time-based movement in 3D in much the same way as we do in two dimensions. As an example, let's use a little 3D vector math to calculate a target vector and work out the intermediate coordinates for a projectile weapon (see Figure 8-3).

Figure 8-3. Calculating a target vector

Soldier Alpha has walked a few meters away from his original position in Figure 8-2, and is now standing at point (-6, 2, 0). The spy droid is still hovering at (7, 5, 10), monitoring Alpha's actions. Fortunately Alpha's acute hearing (or the player's speakers) pick up the faint whirring noise of its antigravity engine and he decides to take out the droid. To fire at the droid, Alpha needs to calculate a vector from his shoulder-mounted plasma rifle to the droid's location.

Figure 8-3. Calculating a target vector

Alpha may be standing over point (-6, 2, 0), but his shoulder is 2 meters above the ground at point (-6, 2, 2), so this is the starting point for the vector calculation. The vector to his target is produced by subtracting the droid's position—point B at (7, 5, 10)—from the starting point A at (-6, 2, 2), giving us a target vector of (13, 3, 8). Normalizing this vector produces a heading vector that can be used in time-based movement. Listing 8-4 shows how to do these calculations in code.

Listing 8-4. Creating a Target Vector from gameobjects.vector3 import *

plasma_speed = 100. # meters per second

AB = Vector3.from_points(A, B) print "Vector to droid is", AB

distance_to_target = AB.get_magnitude()

print "Distance to droid is", distance_to_target, "meters"

plasma_heading = AB.get_normalized() print "Heading is", plasma_heading

Running Listing 8-4 produces this output:

Distance to droid is 15.5563491861 meters

Heading is (0.835672, 0.192847, 0.514259)

If we use these values to render a plasma bolt in a game, we can calculate how far the plasma bolt has moved since the previous frame by multiplying the heading vector by the time passed since the previous frame and the speed of the plasma bolt. Adding the result to the bolt's current location gives us its new location. The code would look something like this:

bolt_location += plasma_heading * time_passed_seconds * plasma_speed

Before you can create 3D projectiles in a Pygame application, you first have to learn how to turn a 3D coordinate into a 2D coordinate in order to render it to the screen—which is the topic of the next section.

Was this article helpful?

0 0

Post a comment