1
This commit is contained in:
46
backend/src/main/java/com/zombie/game/server/GameLoop.java
Normal file
46
backend/src/main/java/com/zombie/game/server/GameLoop.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package com.zombie.game.server;
|
||||
|
||||
import com.zombie.game.model.GameWorld;
|
||||
|
||||
public class GameLoop implements Runnable {
|
||||
private String roomId;
|
||||
private GameWorld world;
|
||||
private GameWebSocketServer server;
|
||||
private volatile boolean running;
|
||||
private static final int TICK_RATE = 30;
|
||||
private static final long TICK_INTERVAL = 1000 / TICK_RATE;
|
||||
|
||||
public GameLoop(String roomId, GameWorld world, GameWebSocketServer server) {
|
||||
this.roomId = roomId;
|
||||
this.world = world;
|
||||
this.server = server;
|
||||
this.running = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
long lastTime = System.currentTimeMillis();
|
||||
|
||||
while (running) {
|
||||
long now = System.currentTimeMillis();
|
||||
long delta = now - lastTime;
|
||||
|
||||
if (delta >= TICK_INTERVAL) {
|
||||
float dt = delta / 1000.0f;
|
||||
world.update(dt);
|
||||
server.broadcastGameState(roomId, world);
|
||||
lastTime = now;
|
||||
} else {
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user