0

I want to move 2 characters simultaneously on screen when their respective keys are pressed.

I am making a java swing game. Wherein I want take inputs from 2 players using "AWSD" and another using "up down right left arrow" . I want both the character to move simultaneously when pressed their respective keys.I thought of making 2 threads and calling them everytime the key is pressed, but isn't working as expected. Any Solutions?

  • 1
    You don't use threads for this type of Swing animation, not directly. You should be using Swing Timers instead which uses background threading in a Swing-thread-safe manner. – Hovercraft Full Of Eels Nov 26 '22 at 14:09
  • 1
    Any of the answers to this question, [How to make an image move while listening to a keypress in Java](https://stackoverflow.com/questions/6887296/how-to-make-an-image-move-while-listening-to-a-keypress-in-java) can be used to move two sprites independently of each other. Note that the answers use key-bindings which are much preferred compared to using key listeners. – Hovercraft Full Of Eels Nov 26 '22 at 14:30
  • Swing is a GUI. GUIs tend to be event-driven. This means that everything we do is not being done in a long-running thread, it is done as a response to an event. "Key Pressed" is such an event. – Mike Nakis Nov 26 '22 at 15:30
  • 1
    @MikeNakis: while I agree with what you state above, if a sprite is moved only on keypress, then its speed and behavior is dependent on the OS, which usually means that the sprite will move one delta on initial keypress followed by a delay and then will continue to move further if the keypress is held. In order to avoid the initial delay and in order to better control sprite animation speed, and also to allow continuous motion that changes direction based on keypress, better to use a Swing Timer to control the animation. The keypress can start and stop the timer and can control direction. – Hovercraft Full Of Eels Nov 26 '22 at 15:55
  • @HovercraftFullOfEels of course this is all true. But a) it still requires first responding to the events, so all of what you have written can be thought of as improvements, and b) I would be willing to bet that Taher Afsar will already have a very high sense of accomplishment if he/she manages to just handle the events. – Mike Nakis Nov 26 '22 at 16:20

1 Answers1

0

To make several character move simultaneously you do not need threading at all. What you need is a game loop, which

  • checks events
  • calculates the world
  • renders the world

If you know there are two characters, it means when checking the events you need to figure out player controls for two characters. When you calculate the world, you need to figure out new positions for both of the characters. And finally render everything so the user can see the new world. This needs to be repeated fast enough to have a smooth movement.

Queeg
  • 7,748
  • 1
  • 16
  • 42