如何在java中制作流畅的动画而不是口吃 [英] How can I make a smooth animation in java instead of a stuttering

查看:36
本文介绍了如何在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

例如,也许看看

这篇关于如何在java中制作流畅的动画而不是口吃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆