我正在用javaFX制作旧版Asteroids游戏的非常基本的版本,以重新开始编程。当生成小行星和子弹(类中的对象)时,我将它们保存在列表中。我试图让这些小行星在屏幕上移动,但是我似乎找不到如何从对象中调用方法的方法,仅针对列表中的最后一个对象。如果我使用list.forEach(object :: method)我可以使小行星运动,但是每次调用forEach方法都会改变所有物体的速度,这当然是不希望的。我只想在生成列表时为列表中的最后一项调用速度方法(floatSpeed)。在这里我可能有什么选择?
因此,我尝试使用自己的for循环在对象之间循环,并使用IF语句使那些Point2D速度为x:0 y:0的对象运动,但这是行不通的,因为它永远不会得到从if语句为true。 getVelocity方法仅以Point2D格式返回对象的当前速度。
for (GameObject Asteroid : asteroids){
if(Asteroid.getVelocity() == new Point2D(0,0)){
Asteroid.floatSpeed();
System.out.println("asteroid moving");
}
到目前为止,这是我使小行星运动的结果,但是每次调用forEach循环时,它们都会更新速度。
private List<GameObject> bullets = new ArrayList<>();
private List<GameObject> asteroids = new ArrayList<>();
private void addAsteroid(GameObject Asteroid, double x, double y){
asteroids.add(Asteroid);
addGameObject(Asteroid,x,y);
}
private void addGameObject(GameObject object, double x, double y){
object.getView().setTranslateX(x);
object.getView().setTranslateY(y);
root.getChildren().add(object.getView());
}
if (Math.random() < 0.01){
addAsteroid(new Asteroid(), Math.random() * root.getPrefWidth(), Math.random() * root.getPrefHeight());
asteroids.forEach(GameObject::floatSpeed);
}
答案 0 :(得分:2)
使用以下代码行在 asteroids 数组的最后一个对象上调用 floatSpeed():
asteroids.get(asteroids.size()-1).floatSpeed();
asteroids.get()返回指定索引中的对象。
asteroids.size()返回列表的大小。
索引从0开始,因此您需要从列表大小中删除1。
从列表中获取对象时,只需调用方法 floatSpeed()。