JavaFX Sprites and Animation


Whenever I find time I try to play with game programming and AI. I have so many old books relating to game programming and noticed how often old algorithms and concepts still apply today. Many who start off with programming games will decide on the perspective or display type that the player will experience. Most people are familiar with platform games or also known as side-scroller type games (Mario Bros.).  I wanted to see how easy it would be to create something in JavaFX and so, over the weekend I put together a simple demo to demonstrate a simple side-scroller.  Thanks to Silveira Neto‘s blog site which helped me realize how easy animation was in JavaFX. To run the demo click the link below the image. The princess demo is my daughter walking and the background is her 3 foot doll house made to look 30 feet high! Click on the image to go to the blog entry.



left arrow key – walk left
right arrow key – walk right
up arrow key – freeze walking position
down arrow key – stand still

Princess Demo

Princess Demo

Click here to launch JavaWebstart of Princess Demo

The Problem

  1. Create a player sprite to be rendered and managed onto the game world
  2. Create a set of sprites.
  3. Create a game loop and game world

The Solution

  1. Create a class called Player
  2. Draw or take pictures of the character in the game
  3. Create a game world. Use JavaFX Timeline with keyframes to listen for key strokes, update sprites and render onto the scene.

Create a class called Player

public class Player extends ImageView {
    public-init var currentState:Integer;
    public-init var currentFrame:Integer;
    public-init var currentDirection:Integer;

    public function walkRight():Void {
        x += 7;
        currentDirection = 1;
        image = right[++currentFrame mod 9];
    public function walkLeft():Void {
        x -= 7;
        currentDirection = -1;
        image = left[++currentFrame mod 9];
    public function stand():Void {
        if (currentDirection == -1){
            image = standLeft;
        } else {
            image = standRight;

Create Sprites

I am not an artist and many sprites are often hard to get, so I decided to take pictures of my daughter in her PJs with a backpack and her doll house as the background of the game. My wife thought how strange it was while we were doing stop action photography. Ten images were snapped including her standing. Most of my time spent was creating transparent images. Next time I will use blue screen for easy background removal. Lastly I horizontally flip the images to make a set of images facing the other direction.

Creating the Game World

 * Main.fx
 * Created on Feb 14, 2009, 10:00:20 AM

package carlfx2;

import carlfx2.player.Player;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

// keyboard
var    upkey = false; //
var rightkey = false; // go right
var  downkey = false; // stop
var  leftkey = false; // go left
var spacekey = false; // jump

// the ground
def ground = Line {
    startX: 0,
    startY: 200
    endX: 300,
    endY: 200
    strokeWidth: 1
    stroke: Color.GREEN

// house background
def house = ImageView{
    image: Image {
        url: "{__DIR__}images/background.png"

// player sprite
var player = Player{
    x: 150
    y: 200 - carlfx2.player.standRight.height
    onKeyPressed: function(e:KeyEvent){
        if (e.code == KeyCode.VK_DOWN) {
            downkey = true;
            upkey = false;
            leftkey = false;
            rightkey = false;
        } else
        if (e.code == KeyCode.VK_UP) {
            upkey = true;
            downkey = false;
            leftkey = false;
            rightkey = false;
        } else
        if (e.code == KeyCode.VK_LEFT) {
            leftkey = true;
            upkey = false;
            downkey = false;
            rightkey = false;
        } else
        if (e.code == KeyCode.VK_RIGHT) {
            rightkey = true;
            leftkey = false;
            upkey = false;
            downkey = false;
        if (e.code == KeyCode.VK_SPACE){
            spacekey = true;
    } // onKeyPressed

// game world / scene contents
var gameWorld = [house, ground, player];

// game loop
var gameLoop = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames: KeyFrame {
        time: 1s / 10
        action: function() {
            // todo: check collision before next move
            if(rightkey) {
            if(leftkey) {
            if(downkey) {

// game stage
Stage {
    title: "Princess Demo",
    width: 400,
    height: 250
    visible: true
    scene: Scene{
        fill: Color.BLACK


This demonstrates how easy it is to render JavaFX artifacts.

I hope you will enjoy this little demo. Any comments are welcome.


13 thoughts on “JavaFX Sprites and Animation

  1. Pingback: JavaFX Sprites and Animation « JFXStudio: sketch, hack, share

  2. JCS

    hi, i wanna build a platformer game, but i don’t really understand the way you use the sprites, usually, in C#, i have the sprite strip, and then, i show part of the image splited on a vector, but here, i don’t know how to load the image and do that, and have single images would be annoying cuz of the amount of characters

    thanks for the tutorial


  3. carldea Post author


    I hope this helps:

    // load all sprites for an individual player.
    public-read def standRight = Image {
            url: "{__DIR__}images/gwalkright/standright.png"
    public-read def right =
    for(i in [0..9]) {
        Image {
            url: "{__DIR__}images/gwalkright/right{i}.png" }
    public-read def standLeft = Image {
            url: "{__DIR__}images/gwalkleft/standleft.png"
    public-read def left  =
    for(i in [0..9]) {
        Image {
            url: "{__DIR__}images/gwalkleft/left{i}.png"  }


  4. Don Osborne

    Wow, is all I can say thanks, This is what I have been trying to do for some time now, Now maybe things will start to fall into place.

  5. Don Schenck

    Carl — I did a copy and paste with two small changes: My project is called MTT, and I changed Player to Target.

    I get the same error on two lines (in my NetBeans IDE). The lines are:

    y: 200 – mtt.Target.standRight.height

    The error is:

    “non-static variable standRight cannot be referenced from a static context”

  6. carldea Post author


    Your welcome!
    I plan to update some of my blog entries to use the latest of JavaFX.
    Whew… I think I’ve taken a long enough break. I plan to get back into blogging.


  7. rodanmuro

    Hi. Thanks for your ideas i like it. But Im trying to run the princess_Demo.jar and I cant because the jvm show this “ unknown protocol:socket”. Do you know how can i fix this??? Thank you very much.

  8. Pingback: JavaPins

  9. Alex

    Please what language is used here? I thought JavaFX worked only with Java?
    Thanks in advance

  10. carldea Post author

    When I blogged about JavaFX at the time is was another language called JavaFX script JavaFX 1.x. This script language used to run on top of Java. Starting with JavaFX 2.x and JavaFX 8 they are now part of Java as APIs. Please look at more recent blog post.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s