I have this code to create an ArrayList with all the pixel locations where there is actually a pixel (alpha != 0).
The code is as follows:
public ArrayList<Point> getPixels() {
ArrayList<Point> output = new ArrayList<Point>();
Image frameImage = img.getCurrentFrame();
for (int FIx = 0; FIx <= img.getWidth(); FIx++) {
for (int FIy = 0; FIy <= img.getHeight(); FIy++) {
if (frameImage.getColor(FIx, FIy).getAlpha() != 0.00f) {//<-- Error
output.add(new Point(FIx, FIy));
}
}
}
return output;
}
The loop can complete fine several times, without any error but on a supposedly random time it is ran, it gives the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 32768
at org.newdawn.slick.Image.getColor(Image.java:1248)
at com.SourCherry.games.KittySniper.Enemy.Kitten.getPixels(Kitten.java:197)
I have labelled the line mentioned (Kitten.java:197) with a comment.
If anything else is required to help solve this problem, please ask in the comments. Thanks.
This looks like the problem to me:
for (int FIx = 0; FIx <= img.getWidth(); FIx++) {
for (int FIy = 0; FIy <= img.getHeight(); FIy++) {
You're assuming that it's got pixels in a range that includes getWidth
and getHeight
. I strongly suspect these are exclusive upper bounds:
for (int FIx = 0; FIx < img.getWidth(); FIx++) {
for (int FIy = 0; FIy < img.getHeight(); FIy++) {
So for example, an image with a width of 3 should have valid X values of 0, 1 and 2 - not 3.
Admittedly this depends on exactly what org.newdawn.slick.Image
does, and that's a class I'm not familiar with - but it's a reasonable starting point. (It's a shame that clearly that method doesn't validate its inputs - it should throw a different exception, but it's still your programming error.)