Game Development Reference
In-Depth Information
We will now add simple physics simulation code that makes use of the new physics
attributes, namely, velocity , terminalVelocity , friction , and acceleration :
1.
Add the following import to AbstractGameObject :
import com.badlogic.gdx.math.MathUtils;
2.
Furthermore, add the following code to the same class:
protected void updateMotionX (float deltaTime) {
if (velocity.x != 0) {
// Apply friction
if (velocity.x > 0) {
velocity.x =
Math.max(velocity.x - friction.x * deltaTime, 0);
} else {
velocity.x =
Math.min(velocity.x + friction.x * deltaTime, 0);
}
}
// Apply acceleration
velocity.x += acceleration.x * deltaTime;
// Make sure the object's velocity does not exceed the
// positive or negative terminal velocity
velocity.x = MathUtils.clamp(velocity.x,
-terminalVelocity.x, terminalVelocity.x);
}
protected void updateMotionY (float deltaTime) {
if (velocity.y != 0) {
// Apply friction
if (velocity.y > 0) {
velocity.y = Math.max(velocity.y - friction.y *
deltaTime, 0);
} else {
velocity.y = Math.min(velocity.y + friction.y *
deltaTime, 0);
}
}
// Apply acceleration
velocity.y += acceleration.y * deltaTime;
// Make sure the object's velocity does not exceed the
// positive or negative terminal velocity
 
Search WWH ::




Custom Search