I am making a game in which there will be many enemies on the screen. Here is part of the code so far:
private boolean update() {
pIndex += cSpd;
if (pIndex > path.length) return true;
cX = path[pIndex].x;
cY = path[pIndex].y;
return false;
}
The problem is that if there are too many enemies/objects on screen, it will throw an exception. (I don’t know the precise amount of “too many,” but I will definitely need to have more than this amount.) Here is the exception:
Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException: 3040
at Game$GamePanel$Circle.update(Game.java:152)
at Game$GamePanel$Circle.access$1(Game.java:149)
at Game$GamePanel.paintComponent(Game.java:110)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
...
I understand what it means. Line 152 is:
cX = path[pIndex].x;
However, this is confusing because the line right before it is:
if (pIndex > path.length) return true;
I don’t understand why this is happening. pIndex and the other variable aren’t static, so I don’t know how other Circles could affect it. Strangely, the index is always 3040 when it throws this exception. How can I fix this problem?
That does not return if
pIndexis exactlypath.length, which is causing the exception.The array index can only go upto array-length minus 1.