Game Development Reference
In-Depth Information
particle->getPosition(&force);
force -= other->getPosition();
// Calculate the magnitude of the force.
real magnitude = force.magnitude();
magnitude = real_abs(magnitude - restLength);
magnitude *= springConstant;
// Calculate the final force and apply it.
force.normalize();
force *= -magnitude;
particle->addForce(force);
}
The generator is created with three parameters. The first is a pointer to the object
at the other end of the spring, the second is the spring constant, and the third is the
rest length of the spring. We can create and add the generator using this code:
Particle a, b;
ParticleForceRegistry registry;
ParticleSpring ps(&b, 1.0f, 2.0f);
registry.add(&a, ps);
Because it contains data that depends on the spring, one instance cannot be used for
multiple objects, in the way that the force generators from chapter 5 were. Instead we
need to create a new generator for each object. 1
Notice also that the force generator (like the others we have met) creates a force
for only one object. If we want to link two objects with a spring, then we'll need to
create and register a generator for each.
Particle a, b;
ParticleForceRegistry registry;
ParticleSpring psA(&b, 1.0f, 2.0f);
registry.add(&a, psA);
1. Strictly speaking, we can reuse the force generator. If we have a set of springs, all connected to the same
object and having the same values for rest length and spring constant, we can use one generator for all of
them. Rather than try to anticipate these situations in practice, it is simpler to assume that instances cannot
be reused.
Search Nedrilad ::




Custom Search