Strange Behavior of getSubImage()

Hi Guys, How are you all? I’m new here so, please be patient ;D
I am being a game dev just about 6 months from now but I already have some experience in Java programming. Recently I took some courage and start to make (and finish) my first serious game. But today I had some trouble with the method getSubImage which is driving me crazy.

For some reason the getSubImage crop only the (0, 0) position of the SpriteSheet, no matter if I change those values on :

 defaultButton = buttons.crop(0, 0, 200, 50); 

and

 defaultButtonPressed = buttons.crop(0, 0, 200, 50); 

I Just discovered about this Java method (getSubImage) a few days ago, and i think this could help me alot. In the past I did all in the hard way, so I’m not sure if I’m using this correctly. Any ideas?

(Thank you. My english is not that good, so I’m using google translate to help me a little bit.)


public class Art {

	private static SpriteSheet buttons;

	public static BufferedImage defaultButton;
	public static BufferedImage defaultButtonPressed;

	public static void loadAllResources() {
		buttons = new SpriteSheet("/art/gui/components/buttons.png");

		defaultButton = buttons.crop(0, 0, 200, 50);
		defaultButtonPressed = buttons.crop(0, 0, 200, 50);
	}
}



public class SpriteSheet {
	private BufferedImage image;

	public SpriteSheet(String path) {
		load(path);
	}

	private void load(String path) {
		try {
			image = ImageIO.read(SpriteSheet.class.getResource(path));
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Erro ao carregar SpriteSheet");
		}
	}

	public BufferedImage crop(int x, int y, int spriteWidth, int spriteHeight) {
		return image.getSubimage(x, y, spriteWidth, spriteHeight);
	}
}

Are you aware both images are fetched using the same coordinates?

Man, I’m not that noob :wink:
Look what I’ve said before:

[quote]For some reason the getSubImage crop only the (0, 0) position of the SpriteSheet, no matter if I change those values on
[/quote]
I pasted a code sample so you guys could visualize the problem.
If I change those values, no matter if is (0, 0) or (1, 0) or (1, 2), the getSubImage will only get from (0, 0)

(Sorry if this sound rude, was not the intention :))

I just notice that when I change, for example the value of x, it increases pixel by pixel to the right side in the image. It made me think: The parameters must be getSubImage (x * spriteWidth, y * spriteHeight, spriteWidth, spriteHeight). And it was exactly that!
So the code looks like this:


public BufferedImage crop(int x, int y, int spriteWidth, int spriteHeight) {
		return image.getSubimage(x * spriteWidth, y * spriteHeight, spriteWidth, spriteHeight);
}

I think this issue despite being very silly was a bit tricky for those who are starting out with game development. But still, it was nice to have posted this question here, now no one will get stuck in it again like me. Anyway, thanks for trying to help RobinB :slight_smile: