JavaFX Sprites and Animation


Introduction

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.

Enjoy!

Commands:

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
    currentDirection:1
    currentFrame:0
    image:carlfx2.player.standRight
    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) {
                player.walkRight();
            }
            if(leftkey) {
                player.walkLeft();
            }
            if(downkey) {
                player.stand();
            }
        }
    }
}

gameLoop.play();

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

Conclusion

This demonstrates how easy it is to render JavaFX artifacts.

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

Advertisement

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

    JCS

  3. carldea Post author

    JCS,

    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"  }
    };
    

    -Carl

  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
    image:mtt.Target.standRight

    The error is:

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

  6. carldea Post author

    Don,

    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.

    -Carl

  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 “java.net.MalformedURLException: 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

    Alex,
    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.

    Carl

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s