Skip to content
Advertisement

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

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

Advertisement

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:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement