Game Development Reference
In-Depth Information
The next block of code in the for loop computes the springs forces acting on each
particle. There are several steps to this, so we'll go through each one. First the loop is
set up to step through the list of springs. Recall that each spring is connected to two
particles, so each step through the loop will compute a spring force and apply it to two
separate particles.
Within the loop, the variable j is used as a convenience to temporarily store the index
that refers to the Object to which the spring is attached. For each spring j is first set to
the spring's End1 property. A temporary variable, pt1 , is then set equal to the position
of the Object to which j refers. Another temporary variable, v1 , is set to the velocity of
the Object to which j refers. Next, j is set to the index of End2 , the other Object to
which the current spring is attached, and that object's position and velocity are stored
in pt2 and v2 , respectively. This sort of temporary variable use isn't necessary, of course,
but it makes the following lines of code that compute the spring force more readable in
our opinion.
vr is a vector that stores the relative velocity between the two ends of the spring. We
compute vr by subtracting v1 from v2 . Similarly, r is a vector that stores the relative
distance between the two ends of the spring. We compute r by subtracting pt1 from
pt2 . The magnitude of r represents the stretched or compressed length of the spring.
The change in spring length is computed and stored in dl as follows:
dl = r.Magnitude() - Springs[i].InitialLength;
dl will be negative if the computed length is shorter than the initial length of the spring.
This implies that the spring is in compression and should act to push the particles away
from each other. A positive dl means the spring is in tension and should act to pull the
particles toward each other. The line:
f = Springs[i].k * dl;
computes the corresponding spring force as a function of dl and the spring constant.
Note that f is a scalar and we have not yet computed its line of action, although we know
it acts along the line connecting the particles at End1 and End2 . That line is represented
by r , which we computed earlier. And the spring force is just f times the unit vector
along r . Since we're including damping, we have to use the spring-damper equation for
the total force acting on each particle, which we call the vector F . F is computed as
follows:
F = (r*f) + (Springs[i].d*(vr*r))*r;
The first term on the right side of the equals sign is the Hooke's law-based spring force,
and the second term is the damping force. Note here that r is a unit vector previously
computed using the line:
r.Normalize();
Search Nedrilad ::




Custom Search