【发布时间】:2017-05-08 10:04:04
【问题描述】:
所以我需要帮助让我的角色移动得更顺畅。 问题是当我按下一个键时角色移动了一个像素,然后在一秒钟后他“顺利”地运行。我该如何解决它,这样我就不需要等待那一秒钟,而他从一开始就顺利运行? 在此之前,我感谢任何帮助和感谢!
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(x, y, 30, 30);
update();
}
private boolean[] KB = new boolean[4];
public void update(){
if(KB[0] = true)
{
y -= 10;
}
if(KB[1] = true)
{
x -= 10;
}
if(KB[2] = true)
{
y += 10;
}
if(KB[3] = true)
{
x +=10;
}
repaint();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W)
{
KB[0] = true;
}
if(e.getKeyCode() == KeyEvent.VK_A)
{
x -= 10;
}
if(e.getKeyCode() == KeyEvent.VK_S)
{
y += 10;
}
if(e.getKeyCode() == KeyEvent.VK_D)
{
x += 10;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
【问题讨论】:
-
if(KB[0] = true)应该是if(KB[0] == true)吗?或者只是if(KB[0]) -
为什么
keyPressed有不同的逻辑? PS:在paintComponent中调用 repaint() 可能也不是最好的主意 -
您需要使用
Swing Timer来控制动画。见Motion Using the Keyboard。KeyboardAnimation.java示例展示了如何使用Swing Timer实现您可以控制的流畅动画。
标签: java swing game-physics paintcomponent