How to change the coordinates of an object with the press of a key?

145 views Asked by At

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.)

1

There are 1 answers

3
Rafay On BEST ANSWER

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
    {
    }
}