## Little Physics in 3D

In Chapter 8 we developed a very simple point-mass-based physics model in 2D. Here's the good news: everything works the same in 3D!

Positions are now 3D vectors instead of 2D vectors. We just add a z-coordinate.

Velocities are still expressed in meters per second on each axis. We just add one more component for the z-axis!

Accelerations are also still expressed in meters per second per second on each axis. Again, we just add another coordinate.

The pseudocode in Chapter 8 describing a physics simulation update looked like this:

Vector2 position = new Vector2(); Vector2 velocity = new Vector2(); Vector2 acceleration = new Vector2(0, -10); while(simulationRuns) {

float deltaTime = getDeltaTime();

velocity.add(acceleration.x * deltaTime, acceleration.y * deltaTime); position.add(velocity.x * deltaTime, velocity.y * deltaTime);

We can translate this into 3D space by simply exchanging the Vector2 instances with Vector3 instances:

Vector3 position = new Vector3(); Vector3 velocity = new Vector3();

Vector3 acceleration = new Vector3(0, -10, 0); while(simulationRuns) {

float deltaTime = getDeltaTime();

velocity.add(acceleration.x * deltaTime, acceleration.y * deltaTime, acceleration.z * deltaTime);

position.add(velocity.x * deltaTime, velocity.y * deltaTime, velocity.z * deltaTime);

And that is all there is to it. This simple physics model is again sufficient for many simple 3D games. In the final game of this book we will not even use any acceleration, because of the nature of the objects in the game.

More complex physics in 3D (and 2D) are, of course, harder to implement. For this purpose you'd usually use a third-party library instead of reinventing the wheel yourself. The problem on Android is that Java-based solutions will be much too slow due to the heavy computations involved. There are some solutions for 2D physics for Android that wrap native C++ libraries like Box2D via the Java Native Interface (JNI), providing the native API to a Java application. For 3D physics there's a library called Bullet. However, there don't exist any usable JNI bindings for this library yet. Those topics are well outside of the scope of this book, though, and in many cases we don't need any sophisticated rigid-body physics.