首页 > 解决方案 > 如何仅延迟特定方法?

问题描述

我仍然是一个非常早期的编码员,并且仍然不了解有关 java 的一切,所以我的代码仍然有点混乱,对此感到抱歉。我正在用图形 g 类制作一个简单的平台游戏,我试图弄清楚如何在不暂停整个脚本的情况下延迟方法。

我已经尝试过 Thread.sleep() 和 TimeUnit.SECONDS.sleep() 但这两个都冻结了当时运行的其他方法,以及保持游戏运行的 Timer。


    private static Timer timer;
    private int delay = 10;

    public Gameplay() {
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        timer = new Timer(delay, this);
        timer.start();
    }

    public void moveDown() {
        if (play == true) {
            Playsound("drop");
            dropping = true;
            //pause here for 1 second without freezing timer or other running methods
            dropping = false;
        }
    }

我希望程序在等待时继续运行,但我尝试过的东西总是冻结整个程序

标签: java

解决方案


我身边的一招

public void moveDown() {
    if (play == true) {
        Playsound("drop");
        dropping = true;
        //create a thread which will execute your method and set sleep on that thread

        dropping = false;
    }

推荐阅读