LibGDX渲染方法问题****** FIXED *******

时间:2015-08-14 15:19:57

标签: java libgdx

 Attempt to read from field 'com.badlogic.gdx.utils.Array com.rocketdefender.GameWorld.GameWorld.rockets' on a null object reference

我一直在尝试渲染一系列火箭并更新它们,以便它们在屏幕上向下移动但是当我在移动设备上运行时它就会出现这个错误。在运行程序之前没有错误。我试图修复,但不知道为什么数组首先为空。

public class GameWorld {

    public Array<Rocket> rockets;
    private long lastDropTime = 0;
    private Rocket rocket;
    private SpriteBatch batch;

    public GameWorld(){
        rockets = new Array<Rocket>();
    }

    public void update(float delta){

        Iterator<Rocket> iter = rockets.iterator();
        while(iter.hasNext()) {
            Rocket nextRocket = iter.next();
            nextRocket.y -= 200 * delta;
            if (nextRocket.y + 64 < 0) iter.remove();
        }
        if(TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnRocket();

    }

    public void spawnRocket(){
        rocket = new Rocket(20, 30);
        rockets.add(rocket);
        lastDropTime = TimeUtils.nanoTime();
    }
    ...
}
public Rocket(int width, int height) {
    rocket = new Rectangle();
    rocket.x = MathUtils.random(0, 800- (width * 2));
    rocket.y = 100;
    rocket.width = width;
    rocket.height = height;
}

GameRenderer Class

    public class GameRenderer {

    private GameWorld myWorld;

    private OrthographicCamera cam;
    private SpriteBatch batch;

    private int GameHeight;

    public GameRenderer(GameWorld world, float GameHeight) {
        myWorld = world;
        this.GameHeight = (int) GameHeight;

        cam = new OrthographicCamera();
    cam.setToOrtho(false, 136, 204);

    batch = new SpriteBatch();
    // Attach batch to camera
    batch.setProjectionMatrix(cam.combined);
}


    public void render(){
        cam.update();

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        for(Rocket nextRocket: myWorld.rockets) {
              batch.draw(AssetLoader.rocket, nextRocket.x, nextRocket.y);
        }
        batch.end();
    }
}

0 个答案:

没有答案