I am currently making a "Hero" move around in eclipse by repainting it in an altered X coordinate if a key is pressed. This is working, however the movement is rough and even appears laggy. I would really appreciate any help / advice, the code looks long but it is really basic.
Code for the level
JFrame window = new JFrame("Level");
Hero hero = new Hero(0, 800);
public Level()
{
this.setFocusable(true);
this.addKeyListener(this);
window.add(this);
window.setSize(1400, 980);
window.setLocation(40,20);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void paint(Graphics g)
{
try {
Image i = ImageIO.read(getClass().getResource("/Sprites/Background.jpg"));
g.drawImage(i, 0, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hero.drawHero(g);
}
@Override
public void keyPressed(KeyEvent kp)
{
if(kp.getKeyCode()==KeyEvent.VK_RIGHT)
{
hero.setxAxis(hero.getxAxis()+5);
this.repaint();
}
if(kp.getKeyCode()==KeyEvent.VK_LEFT)
{
hero.setxAxis(hero.getxAxis()-5);
this.repaint();
}
}
Code for the hero
public class Hero {
int xAxis;
int yAxis;
Image heroImage;
public Hero(int xAxis, int yAxis)
{
super();
this.xAxis = xAxis;
this.yAxis = yAxis;
try {
heroImage = ImageIO.read(getClass().getResource("/Sprites/Pic1.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getxAxis() {
return xAxis;
}
public void setxAxis(int xAxis) {
this.xAxis = xAxis;
}
public int getyAxis() {
return yAxis;
}
public void setyAxis(int yAxis) {
this.yAxis = yAxis;
}
public void drawHero(Graphics g) {
g.drawImage(heroImage, xAxis, yAxis, null);
}
}