如何在java中制作流畅的动画而不是口吃
我正在制作一个练习游戏,当我按下回车键时,会弹出一把刀,我希望它看起来像是在空中飞行.现在每次我点击进入它都会跳过大约一英寸并停止.
I'm making a game for practice and when I hit enter a knife pops up and I want it to look like its flying through air. Right now each time I click enter it skips about an inch and stops.
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onEnter");
am.put("onEnter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Enter pressed
throwKnife = true;
if(move)
{
for(int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
knifeX += i;
repaint();
} catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(knifeX > 1200)
{
throwKnife = false;
move = false;
knifeX = imageX+100;
knifeY = imageY+75;
}
}
throwKnife = true;
}
});
这是在我的绘制组件方法中与以下代码配对
This is paired with the following code in my paint component method
if(throwKnife)
{
g.drawImage(knife, knifeX, knifeY, this);
repaint();
move = true;
}
基于键绑定 API 和 repaint
的使用,我猜你正在使用 Swing,在这种情况下你'正在使用 Thread.sleep
Based on the use of the key bindings API and repaint
, I'm guessing you're using Swing, in which case you're blocking the event dispatching thread with the Thread.sleep
有关原因,请参阅Swing 中的并发
查看 如何使用 Swing 计时器一个简单的解决方案
Have a look at How to use Swing Timers for a simple solution
我还应该指出,ActionListener
将在按住键时重复调用.更好的解决方案是使用标志来指示键何时处于活动状态"和主循环"(如 Swing Timer
)以相应地更新状态
I should also point out that the ActionListener
will be called repeatedly while the key is held down. A better solution would be to use a flag to indicate when the key is "active" and a "main loop" (like a Swing Timer
) to update the state accordingly
当然,这需要你检测key什么时候释放,可以通过再次绑定key来实现,但是对于release.请参阅 KeyStroke.getKeyStroke(int, int, boolean)
了解更多详情
Of course, this will require you to detect when the key is released, which can be achieved by binding the key again, but for release. See KeyStroke.getKeyStroke(int, int, boolean)
for more details
例如,也许看看