animations - Vrekt/Lunar GitHub Wiki
Lets start with the AnimationManager
. This handles storing and playing animations.
Below I have created new SpriteManager
object that will load all of our character animations.
private SpriteManager characters = new SpriteManager("C:\\Path\\To\\File\\characters.png", "Characters");
Now lets start by loading the characters in and assigning the animations.
private Animation up;
private Animation down;
private Animation left;
private Animation right;
Now with the SpriteManager we can put the getMultipleSprites
method to use.
getMultipleSprites
is a method used to get multiple sections of a sprite-sheet all in one call.
getMultipleSprites(int x, int y, int width, int height, Direction direction,
int spriteCount, int xOffset, int yOffset);
As from the java documentation:
/**
* Get multiple images from an image.
*
* @param x the X coordinate.
* @param y the Y coordinate.
* @param width the width
* @param height the height
* @param direction the direction
* @param spriteCount the amount of sprites to get.
* @param xOffset the offset to add/subtract since spacing between sprites can vary.
* @param yOffset the offset to add/subtract since spacing between sprites can vary.
* @return an array of sprites.
*/
BufferedImage[] imagesUp = characters.getMultipleSprites(0, 96, 32, 32, Direction.RIGHT, 3, 0, 0);
BufferedImage[] imagesDown = characters.getMultipleSprites(0, 0, 32, 32, Direction.RIGHT, 3, 0, 0);
BufferedImage[] imagesLeft = characters.getMultipleSprites(0, 32, 32, 32, Direction.RIGHT, 3, 0, 0);
BufferedImage[] imagesRight = characters.getMultipleSprites(0, 64, 32, 32, Direction.RIGHT, 3, 0, 0);
Make sure you set the xOffset
and yOffset
to your needs.
Now lets actually create the animation.
up = new Animation(bup, 20, true, 0);
down = new Animation(bdown, 20, true, 1);
left = new Animation(bleft, 20, true, 2);
right = new Animation(bright, 20, true, 3);
Next we add them to a list for easy use.
List<Animation> animations = new ArrayList<Animation>();
animations.add(up);
animations.add(down);
animations.add(left);
animations.add(right);
Finally we initialize a new AnimationManager
with the animations we created.
am = new AnimationManager(animations);
Now that we have our animations ready lets play them. Usually your player will have a variable telling you what direction they are facing, use this.
Direction d = player.getDirectionFacing();
Now lets play the animation based on what way we are facing.
am.startAnimation(d == Direction.UP ? up : d == Direction.DOWN ? down : d == Direction.LEFT ? left : right);
Next, draw the current frame of the animation.
am.drawPlayingAnimation(graphics, player.getX(), player.getY());
Finally, in the tick method we update the animation.
am.updatePlayingAnimation();