After reading some posts about smoothing key movements, I tried testing it, but I can’t get it to work. Can anyone tell me what I’m doing wrong?
Thanks.
class Test extends JFrame
{
private final int CANVAS_WIDTH = 500;
private final int CANVAS_HEIGHT = 500;
private int x;
private int y;
private boolean left;
private boolean right;
private boolean up;
private boolean down;
public Test()
{
this.setSize( CANVAS_WIDTH, CANVAS_HEIGHT );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setBackground( Color.gray );
this.addKeyListener( new KeyAdapter()
{
public void keyPressed( KeyEvent e )
{
if( e.getKeyCode() == KeyEvent.VK_LEFT )
left = true;
if( e.getKeyCode() == KeyEvent.VK_RIGHT )
right = true;
if( e.getKeyCode() == KeyEvent.VK_UP )
up = true;
if( e.getKeyCode() == KeyEvent.VK_DOWN )
down = true;
move();
}
public void keyReleased( KeyEvent e )
{
if( e.getKeyCode() == KeyEvent.VK_LEFT )
left = false;
if( e.getKeyCode() == KeyEvent.VK_RIGHT )
right = false;
if( e.getKeyCode() == KeyEvent.VK_UP )
up = false;
if( e.getKeyCode() == KeyEvent.VK_DOWN )
down = false;
}
} );
x = CANVAS_WIDTH/2 - 15;
y = CANVAS_HEIGHT/2 - 15;
this.setVisible( true );
}
private void move()
{
if( left )
{
x -= 3;
}
if( right )
{
x += 3;
}
if( up )
{
y -= 3;
}
if( down )
{
y += 3;
}
repaint();
}
public void paint( Graphics g )
{
g.clearRect( 0, 0, 500, 500 );
g.setColor( Color.black );
g.fillRect( x, y, 30, 30 );
}
}