Reputation: 535
I am trying to write a 2d graphical game. In this game I have keyboard inputs to move a square block on a black plane. I order to ensure smooth key motions I want to use Buffered key input. In order to do this I use a boolean array that saves the key strokes.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
/**
* @param args
*/
class Entity
{
int x = 150,y = 150;
int Speed = 5;
}
Entity user = new Entity();
boolean[] keys = new boolean[KeyEvent.KEY_TYPED];
public Main()
{
setSize(800,600);
setLocationRelativeTo(null);
final JPanel display = new JPanel()
{
protected void paintComponent(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.fillRect(user.x, user.y, 30, 30);
}
};
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent arg0)
{
keys[arg0.getKeyCode()] = true;
if(keys[KeyEvent.VK_UP])
{
user.y -= user.Speed;
}
if(keys[KeyEvent.VK_DOWN])
{
user.y += user.Speed;
}
if(keys[KeyEvent.VK_LEFT])
{
user.x -= user.Speed;
}
if(keys[KeyEvent.VK_RIGHT])
{
user.x += user.Speed;
}
setFocusable(true);
repaint();
}
});
//add a action listener
//remember to set the focusable
add(display);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread();
try {
t.sleep(100);
Main m = new Main();
m.setVisible(true);
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In this input the block moves in the correct direction but just twice, then It moves in a different motion and it even Stops moving.
I have searched in all my Java books that I have and it does not help much. How can I get this error fixed?
Upvotes: 0
Views: 1741
Reputation: 94499
Make the boolean[] keys
a local variable so that it does not contain previously pressed keys, which will impact the x,y
coordinates.
public void keyPressed(KeyEvent arg0)
{
boolean[] keys = new boolean[KeyEvent.KEY_TYPED];
keys[arg0.getKeyCode()] = true;
if(keys[KeyEvent.VK_UP])
{
user.y -= user.Speed;
}
else if(keys[KeyEvent.VK_DOWN])
{
user.y += user.Speed;
}
else if(keys[KeyEvent.VK_LEFT])
{
user.x -= user.Speed;
}
else if(keys[KeyEvent.VK_RIGHT])
{
user.x += user.Speed;
}
setFocusable(true);
repaint();
}
If you just want to clear the keys
public void keyPressed(KeyEvent arg0)
{
keys = new boolean[KeyEvent.KEY_TYPED];
keys[arg0.getKeyCode()] = true;
/* Rest of code */
Upvotes: 1