我正在使用JavaFX制作塔防游戏,我目前的问题是在动画计算后更新视图。我尝试制作新的Thread并启动它,但每当我从Canvas触摸GraphicContext时,游戏就崩溃了。我目前的游戏循环类看起来像:
import model.Enemy;
import model.Map;
import model.Player;
import model.Model;
import view.View;
public class GameLoop2 {
private Canvas canvas;
public Integer enemiesNr;
public Integer enemiesSpawnTime;
public Integer spawnedEnemies;
private long lastSpawn;
private ArrayList<Enemy> enemies;
private boolean firstPlay;
private Model model;
private Map map;
public GameLoop2(Canvas mainCanvas, Model m) {
model = m;
map = model.getMap();
canvas = mainCanvas;
enemiesNr = map.getEnemiesNr();
enemiesSpawnTime = model.getMap().getEnemiesSpawnTime();
spawnedEnemies = 0;
lastSpawn = System.currentTimeMillis();
enemies = new ArrayList<>(enemiesNr);
for(int i=0; i < enemiesNr;i++)
enemies.add(i, new Enemy(map.getStartXPosition(), map.getStartXPosition()));
}
private void spawnEnemy() {
if(spawnedEnemies >= enemiesNr)
return;
enemies.get(spawnedEnemies).setAlive(true);
View.drawEnemy(canvas, enemies.get(spawnedEnemies));
spawnedEnemies++;
lastSpawn = System.currentTimeMillis();
}
private void enemyPhysics() {
for(Enemy e: enemies)
if(e.isAlive())
e.physics(1);
}
private void drawEnemies(){
for(Enemy e: enemies)
if(e.isAlive())
View.drawEnemy(canvas,e);
}
private void update() {
canvas.getGraphicsContext2D().restore();
View.drawMap(map, canvas);
drawEnemies();
}
public void start() {
while(true){
// Calculations
long now = System.currentTimeMillis();
if (now - lastSpawn > enemiesSpawnTime) {
spawnEnemy();
}
enemyPhysics();
// Updating View
update();
// View is refreshed after break; statement
if(now - lastSpawn > 6000)
break;
}
}
我也尝试过Service类,但它对我没用。我也想尽可能快地进行捏造,使动作动画效果适合于接近敌人。以允许添加另一个线程(例如背景音乐或计算主塔损坏)的方式制作它会很好。