I have a cat that runs across the screen and stops to scratch in the middle of the screen twice. My current code looks like
private void scratch(){
for (int i = xPos; i < getWidth(); i+=0) {
xPos = i;
// swap images
if (currentImage == nekoPics[0])
currentImage = nekoPics[2];
else if (currentImage == nekoPics[2])
currentImage = nekoPics[4];
else if (currentImage == nekoPics[4])
currentImage = nekoPics[5];
else if (currentImage == nekoPics[5])
currentImage = nekoPics[4];
else if (currentImage == nekoPics[4])
currentImage = nekoPics[5];
else
currentImage = nekoPics[0]
Is there an easier way to make the if else statements than have them going in a huge circle like this?
Thanks in advance (PS : I assume you could do this with a counter of some sort, but I wasn't so sure on how to go about this, any help is appreciated)
I was going to post an answer similar to rcook, using an array. I see it as the simplest solution to understand.
His answer, however, has a slight mistake concerning the array dimensions. I'm posting this for completeness, but credit should be directed to him.
In addition to a Map suggested elsewhere, you could just use an array; you'll need to keep track of the index of the current image:
No 'if' needed after you initialize currentImage and currentImageIndex. I wasn't sure if 1 was a valid index anywhere, if not, anything can go in the 1 slot in the array.
You may keep the index of the current image, and increment it on each iteration, for instance:
or
This requires that images in nekoPics be sorted according to the order of the animation.
It would probably be easier to code if you stop that cat from getting in front of your screen...
Seriously, though, you could solve this by making an object that defines your sequence of pictures.