This has probably been asked before, but I searched the forums and couldn’t find a specific answer…Anyway, I have three images that I want to loop when the up arrow key is pressed, three to loop when down is pressed, same for left and right (making it look like the sprite is walking)…The question is, how would I go about making this loop? Is the while loop best for this sort of thing? I’ve tried a few different things on my own but so far I haven’t been able to make it loop like it should.
what i would do, is to put the sprites in an array, and each frame increment the index of the array, because the game basicly and normally is one big while loop anyway where you handle input, logic and rendering each iteration of the main loop. When the index is equal to the size of the array, you can then reset the index to keep it looping.
This thing is easier with a 1D array. To change the slice method (from the other thread) accordingly is easy to do:
-make it return a 1D array
-change new BufferedImage[cols][rows] to new BufferedImage[cols*rows]
-before the two loops create some variable like int num=0;
-replace slices[x][y] with slices[num]
-add num++; at the end of the inner loop
Alright. Now that you have a 1D array you can define a single animation as a sequence of numbers. Eg {6,7,8,9,25,10,11,12}. A 2D array can hold all those animations (the arrays inside the array doesn’t necessarily have the same length).
If you want to display that animation you don’t need another loop, since you already got a game loop, which handles the logic and draws the stuff… over and over again.
So, in your logic bit you have like… some object which represents like… some little dude. This dude can have different states. When the state changes from one to another you reset the frame index (you set it to 0 - the first frame) and set the animation type (first dimension index) accordingly. If the state didn’t change you increase the frame index. If the frame index isn’t < length anymore you can either change it to 0 (making it loop) or set it to 0 and change the animation type (for making a specific animation stop).
Basically.
If the animation is very simple. Like the walk animation of Rick Dangerous or a Shyguy from Mario… then you only have 3 frames, which are played very quickly… and it doesn’t really matter if you start with the “right” one. In that case you can use some variable, which is increased once each loop and the frame is picked via %3 (or %foo[type].length heh).