我目前正在eclipse中製作一個「英雄」動作,如果按下某個鍵,則在更改的X座標中重新繪製它。這工作,但運動是粗糙的,甚至出現遲緩。我真的很感謝任何幫助/建議,代碼看起來很長,但它確實很基礎。如何在java中使角色順利移動?
代碼級別
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();
}
}
代碼爲英雄
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);
}
}
您是否在事件調度線程(EDT)上運行GUI?如果不是,預計麻煩。 –
不,我不是。你能解釋如何做到這一點? @LewBloch – cwsl26
而我會在哪裏使用它? @LewBloch謝謝你的方式。 – cwsl26