/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package spriteanimation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author Compsci */ public class SpriteAnimation extends Application { private String[] spriteList = {"file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/Right01.png", "file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/Right02.png", "file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/Right03.png", "file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/Right04.png", "file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/Right05.png", "file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/Right06.png"}; private Image img = new Image("file:C:/Users/Compsci/Documents/NetBeansProjects/SpriteAnimation/spritewalk/walkSpriteSheet.png"); private int currentFrame = 0; private int cols = 6; private int frameHeight = 150; private int frameWidth = 104; @Override public void start(Stage primaryStage) { Group root = new Group(); Canvas canvas = new Canvas(512, 512); Scene scene = new Scene(root); root.getChildren().add(canvas); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.WHITE); Timeline animation = new Timeline(); KeyFrame kf = new KeyFrame(Duration.millis(100), e->{ gc.clearRect(0, 0, 512, 512); gc.fillRect(0, 0, 512, 512); int fx = currentFrame % cols * frameWidth; int fy = currentFrame / cols * frameHeight; gc.drawImage(img, fx, fy, frameWidth, frameHeight, 200, 200, frameWidth, frameHeight); //gc.drawImage(new Image(spriteList[currentFrame]), 100, 100); currentFrame++; if (currentFrame > 5) currentFrame = 0; }); animation.getKeyFrames().add(kf); animation.setCycleCount(Timeline.INDEFINITE); animation.play(); primaryStage.setTitle("Sprite Animation"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }