在这个游戏中,我试图让多个激光器在给定坐标处产生,但由于某种原因,每次numLasers大于1时应用程序崩溃。我已经尝试了一切,我真的可以使用一些帮助。 / p>
这是我的代码:
public class LaserSpawn {
private int amountOfVisibleLasers;
private Context context;
private long timeLastCreatedLaser;
private Laser[] holderLaser;
public LaserSpawn(Context context, int numLasers){
this.context = context;
holderLaser = new Laser[numLasers];
this.amountOfVisibleLasers = numLasers;
for(int i = 0; i< numLasers; i++){
holderLaser[0] = new Laser(context, -10, -10);
}
}
public void updatePlayerLaser(boolean shootLaser, float x, float y) {
// Check if a new Laser should be created
if(shootLaser == true) {
if(timeLastCreatedLaser + 100 < System.currentTimeMillis()) {
timeLastCreatedLaser = System.currentTimeMillis();
boolean createdNewLaser = false;
for(int i = 0; i < this.amountOfVisibleLasers; i++) {
if(createdNewLaser == false) {
if(holderLaser[i].isDisposed()) {
this.generateNewLaser(i,x,y);
createdNewLaser = true;
}
}
}
}
}
// Update all the other Lasers
for(int i = 0; i < this.amountOfVisibleLasers; i++) {
if(holderLaser[i].isDisposed() == false) {
holderLaser[i].update();
}
}
}
private void generateNewLaser(int i, float x, float y) {
holderLaser[i].setY(y);
holderLaser[i].setX(x);
}
谢谢!
答案 0 :(得分:3)
我很确定这是你的问题:
holderLaser[0] = new Laser(context, -10, -10);
您只需在数组的第一个位置创建new Laser
。如果您尝试访问第二个,则会获得null pointer exception
。
应该是
holderLaser[i] = new Laser(context, -10, -10);