I'm working on a puzzle game, I've implemented a sprite class that uses an array of images and cycle through the array to draw each frame as required. This works fine!
Here's the original code:
String number;
Image sprite;
ArrayList <ImageIcon> spriteAnimation = new ArrayList();
int _imageCount = 0;
int _animationStart = 0;
public Sprite(String spriteType, int totalFrames){
for(int x =1; x <= totalFrames; x++){
spriteAnimation.add(new ImageIcon("Images/" + spriteType + "/" + spriteType + x + ".png"));
System.out.println("Added " + spriteType + x + ".png to the ArrayList");
}
}
public void updateSprite(){
sprite = spriteAnimation.get(_imageCount).getImage();
System.out.println("image count is " + _imageCount);
if(_imageCount < spriteAnimation.size()-1){
_imageCount += 1;
}else{
_imageCount = _animationStart;
}
}
public Image getSprite(){
return sprite;
}
}
However, after researching the difference between using the method above and using a single sprite sheet (there must be a good reason to use a sprite sheet I thought, and I was right) I've decided to use a single sprite sheet to represent all sprites in my game.
While I fully understand the principle of using the sprite sheet, I cannot get my head around actually drawing the selected part of the sprite sheet. I thought there might be a constructor in the ImageIcon or Image classes that would allow me to do something like pass in the size of the image to be drawn, the x and y co-ordinates to start at and the original sprite sheet as arguments - but apparently not. I'm obviously looking in the wrong place.
I would be very grateful if someone could advise me on how to do this in Java.