O'Reilly logo

LibGDX Cross-Platform Development Blueprints by Indraneel Potnis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Physics and collision

In this section, we will cover how to add realistic physics to the game and collision detection.

Adding physics

Let's add more realistic physics to our game. We will need to keep track of Bob's velocity. Add a velocity variable to the Bob class:

Vector2 velocity; // Bob's velocity

Instantiate and initialize it in the initialize() method:

velocity = new Vector2(0, 0);

Now, when we move the player, we set the velocity to a predefined value. Let's call it maxVelocity and change the X_MOVE_UNITS constant to maxVelocity:

private static final float maxVelocity = 0.1f;

Now, let's update the player's velocity when we press the arrow keys/touch paddles in the update() method:

// move specified units to left if left key is pressed if (isLeftPressed){ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required