Java Reference
In-Depth Information
Building animation with the KeyFrame API
While transition-based animation classes provide a quick and easy way to animate objects in
the scene graph, they expose little control over the way the animation steps are constructed.
For instance, when you build an animation sequence with the TranslateTransition
class, you can only specify the origin and the destination points of the object. The class
automatically fills in the frames in between. This recipe covers keyframe-based animation
techniques. Using this approach, developers are able to take full control over the animation
sequence by specifying the keyframes that make up the animation.
Getting ready
Although optional, it is helpful to be familiar with the transition-based animation presented
in the recipe Creating simple animation with the Transition API, as it includes valuable
information about animation and animation controls. Creating keyframe animation involves
two main classes, Timeline and KeyFrame , found in the package javafx.animation .
Timeline provides overall control of the animation, while KeyFrame lets you assemble the
granular steps that make up the animation.
How to do it...
To create keyframe-based animation, you can declaratively build your timeline by adding
keyframes that describe the steps of your animation. To illustrate how to use keyframe
animation, we will build a simple game where the objective will be to use a paddle that is
moving from side-to-side on the screen to hit a ball. When the paddle hits the ball, you get
one point. Since the code is rather long, it will be presented in chunks. You can get the full
code listing from ch03/source-code/src/animation/KeyFrameAnimDemo.fx .
1. Let's first declare some variables to be used later in the code.
def w = 400;
def h = 200;
var rad = 15.0;
var cx = w / 2;
var cy = h - rad;
var scoreCounter = 0;
def paddleTime = 0.5s;
2. Next, we declare the objects used to display the score.
def score = Text {
textOrigin: TextOrigin.TOP x: w / 2 y: h / 2
font: Font.font("Helvetica", FontWeight.BOLD, 48)
content: bind "{scoreCounter}"
Search WWH ::

Custom Search