Game Development Reference
In-Depth Information
Make the following changes to the Rock class:
@Override
public void update (float deltaTime) {
super.update(deltaTime);
floatCycleTimeLeft -= deltaTime;
if (floatCycleTimeLeft<= 0) {
floatCycleTimeLeft = FLOAT_CYCLE_TIME;
floatingDownwards = !floatingDownwards;
body.setLinearVelocity(0, FLOAT_AMPLITUDE
* (floatingDownwards ? -1 : 1));
} else {
body.setLinearVelocity(body.getLinearVelocity().scl(0.98f));
}
}
These changes represent an almost direct translation from our own physics
simulation to Box2D's one for the rocks' floating-on-water effect. It is crucial to
understand why we have to change this part or else you will probably spend a lot of
time hunting down nasty problems in conjunction with Box2D.
In our previous implementation, the rocks' movement was achieved by directly
modifying its position vector. Since the rocks are now controlled by Box2D, we
would have to change the position of the rock's body using the setTransform()
method instead. Usually, this is a really bad idea as it can confuse Box2D when a
manual change of a body position results in two or more overlapping shapes. These
overlapping shapes, then, can cause quite unpredictable effects such as extreme
accelerations or a disruption of resting objects. So, additional care needs to be taken
if the position and/or angle of the rotation of a body are set directly.
As you can see in the preceding changed code, we are actually not using
setTransform() but setLinearVelocity() . So, the general rule to avoid the
mentioned problems is to tell Box2D about the physical cause to get the desired
effect. This means that we have to express changes in the world through forces,
which in turn are translated into velocities.
After all this, the last modification is to free the allocated memory when appropriate.
Add the following import line to the WorldController class:
import com.badlogic.gdx.utils.Disposable;
 
Search WWH ::




Custom Search