-1

I have to create a small 2D Java tile game for schoolwork and I would like to know how can I move an object with the press of a button.

More specifically, I have an item with ' i ' and ' j ' coordinates in a matrix. After I press ENTER on my keyboard, I want the item to move down by 1 position ( i + 1). If I press ENTER over and over again, the object moves down accordingly. As if the game would be 1 frame/second. How can I do that? I'm kind of new to the Java language and I couldn't find the answer online.

(To make the game with GUI, I followed some tutorials and I'm using the Slick2D library.)

  • You can use an keybinding or a key listener to do this, then simply make the key action edit the `i` and `j` co-ordinates of your item within the array: https://stackoverflow.com/questions/23486827/java-keylistener-vs-keybinding – sorifiend Apr 05 '21 at 22:32
  • There's a lot of info about this on forums, just do some more effort to research. When you come with some code that is not working, we could help you. Currently, you have multiple questions in one – HoRn Apr 06 '21 at 09:10

1 Answers1

0

You want to implement your "update" method and read the input from the container based on the pressed keys. There is a very good article here that will help you going with your game and i think this is what you are trying to implement. Here is a sample code from the above link:

public class MyGame extends BasicGame
{
    public MyGame()
    {
        super("My game");
    }
 
    public static void main(String[] arguments)
    {
        try
        {
            AppGameContainer app = new AppGameContainer(new MyGame());
            app.setDisplayMode(500, 400, false);
            app.start();
        }
        catch (SlickException e)
        {
            e.printStackTrace();
        }
    }
 
    @Override
    public void init(GameContainer container) throws SlickException
    {
    }
 
    @Override
    public void update(GameContainer container, int delta) throws SlickException
    {
        // You need to implement this function
        Input input = container.getInput();
        if (input.isKeyDown(Input.KEY_ENTER))
        {
             // ... your code here ...
        }
    }
 
    public void render(GameContainer container, Graphics g) throws SlickException
    {
    }
}
Rafay
  • 92
  • 8
  • 1
    Can you show any examples of what you describe, or please edit your question to include key information or concepts from the article. External links tend to break over time and the answer may become unhelpful. – sorifiend Apr 06 '21 at 07:43
  • Updated my answer. @ChimiChumi if this helped, you can mark this as accepted answer. Thanks. – Rafay Apr 12 '21 at 07:37
  • yes, sorry I'm new and couldn't find where I could mark my question as solved. – chimichumi Apr 12 '21 at 12:09