Reputation: 1
I recently got into learning Java. I'm trying to get the code to change the picture representing the player at set intervals when a movement key is pressed.
Below is my code. I'm trying to create the image loop within the if statement so that 'currentSprite' will equal 'CharacterRight' 'CharacterRight1' 'CharacterRight2' respectively, then restart from 'CharacterRight' until (player.isMovingRight()) is no longer true.
public void run() {
while (true) {
player.update();
if (player.isMovingRight()) {
currentSprite = characterRight;
}
bg1.update();
bg2.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
It seems like there should be a relatively easy way to accomplish this. I'm sorry if it is a nooby question.
If anyone can help me, I would be eternally grateful.
Upvotes: 0
Views: 146
Reputation: 3215
Since characterRight is an Image and assuming you want your code to work even if you have more images i.e. changes animations etc. What you can do is create list of images and use it, instead to storing each individual image into a variable. Look into JLists for better understanding of how to use Lists.
Solution 1(Not Recommended): you can create variable to track the current frame. (This is not recommended solution). Something like this:
int current_frame = 0;
and in your loop you can use a simple switch statement like this:
switch(current_frame) {
case 0:
currentSprite = characterRight;
current_frame = (current_frame + 1) %4
break;
case 1:
currentSprite = characterRight1;
current_frame = (current_frame + 1) %4
break;
case 2:
currentSprite = characterRight2;
current_frame = (current_frame + 1) %4
break;
case 3:
currentSprite = characterRight3;
current_frame = (current_frame + 1) %4
break;
}
Solution 2(Highly Recommended): preferrably you should use even driven approach. Please refer you this link in order to understand implementation of Key Listeners:
https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
and inside your key listerner you should use image list to change sprites. This is the ideal solution for your case.
Upvotes: 0
Reputation: 285405
Your problem appears to be that you're trying to solve an event-driven GUI problem as if it were a linear console program, and this is not how event-driven programming works. I suggest that you get rid of the while loop, that you get rid of the Thread.sleep bits, and that you instead change the image in response to an event -- whatever event is of relevance to the image, perhaps in response to a MouseListener or a Key Binding -- you'll have to decide this. If this is a Swing GUI, then I'd use JLabels that hold ImageIcons, and simply swap Icons in your event listener.
Upvotes: 1