C H A P T E R 6
■ ■ ■
A physics engine is a software library that simulates how objects move in the real world. Adding physics
to an application provides a way to create animations that appeal to the user's sense of realism. While it
is possible to create animations that have a life-like quality without implementing physics, cracking
open that high school physics topic will provide consistency throughout your application. However, if
the thought of implementing “real life” in your application feels a little out of scope, you can make use of
a third-party library. This chapter will explore what a physics engine can do, and how to use an excellent
open-source library to add physics-based effects to a JavaFX application.
The most obvious use of physics is in video games, but you can create animations for use in any
application. The last example in this chapter shows how physics can be used to create a UI transition.
Computers have been used to simulate the real world from the very beginning. Whether calculating the
motion of an artillery shell or the path of a hurricane, the basic idea is the same. Find a way to express
how the world works in code, setup a scenario, run the program, display the output.
Expressing how the world works in code is the hardest part of the problem. To simplify this
problem, a subset of physics, known as rigid body dynamics , is used. Rigid body dynamics describes how
objects or bodies interact when they move about or collide, but does not consider how a body might
deform as it impacts another body, or how a body might weaken over time. Nor does this subset include
any details about fluids, electromagnetism or other phenomena. This might sound like a large limitation,
but remember the goal is to create eye-catching animations, not actually replicate the real world.
Producing animations where objects fall and collide in a realistic way can produce some amazing
results; you can see this in modern video games that increasingly take advantage of realistic physics,
even to the point where some companies offer specialized hardware to perform these physics
In addition to limiting the calculations to rigid body dynamics, the examples in this chapter also
limit the simulations to 2D space. This limitation makes sense in the current implementation of JavaFX,
as JavaFX is primarily a 2D drawing library at this time.
In general, a simulation works by defining the bodies that exist in the simulated world , each body
has shape, mass, location, rotation, velocity, and an angular velocity. There may also be a number of
attributes that can be used to fine-tune a simulation, such as friction or bounciness. The world in which
these objects reside can also have attributes, such as the force/direction of gravity or a dampening on
the movement of objects.