0
我試圖獲取要渲染爲遊戲畫面的對象數組。我環顧四周,發現了其他人提出的類似問題,但我似乎無法將他們得到的答案應用到我的程序中。Java - 未存儲值的對象數組(範圍?)
該問題似乎發生在嵌套的for-loops中。在試圖解決這個問題時,我在那些for循環的第一行中得到了Java NullPointerExceptions。
package com.frfanizz.agility;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class GameScreen implements Screen {
AgilityGame game;
OrthographicCamera camera;
SpriteBatch batch;
Hero hero;
Spark[] sparkArray;
int totalSparks;
public GameScreen(AgilityGame game) {
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(true, 1920, 1080);
batch = new SpriteBatch();
hero = new Hero(60,540);
//Variables to set spark array
int screenX = 1400;
int screenY = 1200;
int numOfRow = 11;
int numOfCol = 8;
float spacingRow = screenY/(numOfRow + 1);
float spacingCol = screenX/(numOfCol + 1);
int totalSparks = numOfRow*numOfCol;
//Spark array
Spark[] sparkArray = new Spark[totalSparks];
//setting bounds for sparks
int index = 0;
for (int i=0;i<numOfCol;i++) {
for (int j=0; j<numOfRow;j++) {
//sparkArray[index] = new Spark();
sparkArray[index].bounds.x = (float) (60 + spacingCol + ((i)*spacingCol));
sparkArray[index].bounds.y = (float) (spacingRow + ((j-0.5)*spacingRow));
index++;
}
}
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
camera.update();
generalUpdate();
batch.setProjectionMatrix(camera.combined);
batch.begin();
//Rendering code
batch.draw(Assets.spriteBackground, 0, 0);
batch.draw(hero.image,hero.bounds.x,hero.bounds.y);
for (int i=0; i<totalSparks; i++) {
batch.draw(sparkArray[i].image,sparkArray[i].bounds.x,sparkArray[i].bounds.y);
}
batch.end();
}
//Other gamescreen methods
}
的類英雄和星火如下:
package com.frfanizz.agility;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Rectangle;
public class Hero {
public Sprite image;
public Rectangle bounds;
public Hero(int spawnX, int spawnY) {
image = Assets.spriteHero;
image.flip(false, true);
bounds = new Rectangle(spawnX - 16, spawnY - 16, 32, 32);
}
}
和:
package com.frfanizz.agility;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Rectangle;
public class Spark {
public Sprite image;
public Rectangle bounds;
public Spark() {
image = Assets.spriteSpark;
image.flip(false, true);
bounds = new Rectangle();
bounds.height = 32;
bounds.width = 32;
}
}
在for循環中,我已經印刷sparkArray的價值,所以我想我有值的問題,而不是我已閱讀答案的其他問題的參考。 (這裏是我(失敗)引用的問題: Java. Array of objects, Java NullPointerException with objects in array)提前
謝謝!
當我取消註釋該行時,我不再收到NullPointerException,但精靈的數組不會在屏幕上呈現。 – frfanizz 2014-12-19 02:41:37
我得到一行ArrayIndexOutOfBoundsException: sparkArray [row] [col] = new Spark(); – frfanizz 2014-12-19 02:53:33
您可能已經在'for'循環中反轉了行和列邊界(numOfRow/numOfCol)。我發佈的代碼不會產生ArrayIndexOutOfBoundsException。 – gknicker 2014-12-19 07:22:49