LWJGL教程02 - 循环

让Engine类处理循环

上一篇成功创建了窗口,但是循环内的工作在每次创建新程序时仍要重写,很麻烦。

故将循环的工作交给Engine来处理。

先来梳理一下循环内要做什么。

1
2
3
4
5
while(running) {
input();
update();
render();
}

Engine还要负责init()部分的工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
[imports ...]

public class Engine {
static Window.Settings settings;

public static void init(Window.Settings settings) {
Engine.settings = settings;
Window.settings = settings;
}

public static void init() {
Engine.settings = new Window.Settings();
settings.setTitle("Game")
.setWidth(800)
.setHeight(600)
.setColor(0, 0, 0, 255);
Window.settings = settings;
}

public void run() {
Window.createWindow(settings);
Window.setWindowVisible();

long lastTime = System.currentTimeMillis();
int frames = 0;

while(!Window.windowShouldClose()) {
Window.pollEvents();

Window.update();

++frames;

while(System.currentTimeMillis() >= lastTime + 1000L) {
System.out.println(frames + " fps");
lastTime += 1000L;
frames = 0;
}
}
cleanup();
}

private void cleanup() {
Window.cleanup();
}
}

现在测试一下Engine类。

1
2
3
4
5
6
7
8
9
10
[imports ...]

public class TestEngine {
public static void main(String[] args) {
Engine.init();
Window.settings.setTitle("Test Engine")
.setVsync(true);
new Engine().run();
}
}

运行结果

input()的工作,通过ILogic实现。

1
2
3
public interface ILogic {
void input();
}

然后在Engine中添加ILogic

1
public static ILogic logic;
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void init(Window.Settings settings, ILogic logic) {
[...]

Engine.logic = logic;
}
public static void init() {
[...]

logic = new ILogic() {
@Override
public void input() {}
};
}

在循环中调用input()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void run() {
[...]

while(!Window.windowShouldClose()) {
[...]

logic.input();

Window.update();

[...]
}

[...]
}

现在测试一下ILogic

1
2
3
4
5
6
7
8
9
[imports ...]

public class TestLogic implements ILogic {
@Override
public void input() {
if (Window.isKeyPressed(GLFW.GLFW_KEY_SPACE))
System.out.println("Space is pressed");
}
}
1
2
3
4
5
6
7
8
9
10
11
[imports ...]

public class TestEngine {
public static void main(String[] args) {
Engine.init();
Window.settings.setTitle("Test Logic")
.setVsync(true);
Engine.logic = new TestLogic();
new Engine().run();
}
}

按下空格后 - 运行结果


LWJGL教程02 - 循环
https://panxy02.github.io/2024/07/18/lwjgl-02/
作者
52Hertz
发布于
2024年7月18日
许可协议