平铺运动每秒钟

时间:2017-09-28 07:22:16

标签: java slick2d

我有这个更新方法如下所示:

@Override
public void update(Input input, int delta) {

    /* if UP, move player 5 tiles upwards */
    if (input.isKeyPressed(Input.KEY_UP) {
        y -= 5;
        setY(y);
    }

    /* if DOWN, move player 5 tiles downwards */
    if (input.isKeyPressed(Input.KEY_DOWN) {
        y += 5;
        setY(y);
    }

    /* if LEFT, move player 5 tiles to the left */
    if (input.isKeyPressed(Input.KEY_LEFT) {
        x -= 5;
        setX(x);
    }

    /* if RIGHT, move player 5 tiles to the right */
    if (input.isKeyPressed(Input.KEY_RIGHT) {
        x += 5;
        setX(x);  
    }
}

我的世界级的更新循环:

public void update(Input input, int delta) 
throws SlickException {

    // Update every sprite eg. Player, Blocks etc.
    for (Sprite sprite : list) {
        sprite.update(input, delta);
    }  
}

其中setX()setY()只是我班级的设定者,它可以处理玩家应按照切片移动的像素数。每个图块的位数为32像素。

到目前为止,这将我的播放器从一个位置移动到另一个位置5个向下,向上,向左或向右。我想知道他们是否有办法让玩家每0.25秒移动一个瓦片到达目的地?如同每0.25秒,玩家将向左,向右,向下或向上方向移动32个像素。我想要添加它,所以它看起来像玩家滑过瓷砖而不是直接传送到它的位置。

我怎么能用计时器来达到这个目的?我可以使用delta来做到这一点吗?任何形式的帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

看到这个答案:

Java slick2d moving an object every x seconds

你应该明确地使用delta,因为你想在游戏中使用framerate independent motion

答案 1 :(得分:0)

将变量保留在包含时间戳的更新循环之外。

int lastTimestamp;

现在,在你的循环中,创建一个条件,检查自 lastTimetamp 中的时间以来是否已经过了250毫秒。

// Use System.nanoTime() / 1000000L to get current time
if(currentTime >= (lastTimestamp + 250)) {
   movePlayer();
   lastTimestamp = currentTime;
}

现在这个条件应该每0.25秒传递一次。

答案 2 :(得分:0)

我将添加一个Runnable类MoveAnimation,你给它一个 ScheduledExecutorService的。

class MoveAnimation { // the full player movement
    public boolean animationFinished();
    public void animate() {
        if (animationFinished()) {
            throw new Exception(); // there is probably a cleaner way to remove this from the executor
        }
    }
}

class AnimationControl {
    private final ScheduledExecutorService animationSchedule = Executors.newScheduledThreadPool(1);
    public void addMovement(MoveAnimation animation) {
        animationSchedule.scheduleAtFixedRate(animation::animate, 0, 250, TimeUnit.MILLISECONDS);
    }
}

// in the event listener
if (input.keyIsPressed(Input.KEY_LEFT)) {
    animationControl.addMovement(new MoveLeftAnimation(from, to));
}
相关问题