0
我的代碼用於完美工作,但現在當我啓動應用程序時,出現空白屏幕並出現錯誤。LibGDX異常:線程「LWJGL Application」中的異常java.lang.NullPointerException
「異常在線程 「LWJGL應用程序」 在com.mygdx.game.Bunny.render(Bunny.java:70)顯示java.lang.NullPointerException 在com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop (LwjglApplication.java:215) 在com.badlogic.gdx.backends.lwjgl.LwjglApplication $ 1.run(LwjglApplication.java:120)」
這表明到線70:
batch.draw(paddle, paddleRect.x, paddleRect.y);
我的全代碼是:
package com.mygdx.game;
import java.util.Iterator;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
public class Bunny extends ApplicationAdapter {
SpriteBatch batch;
Texture paddle;
Texture blockImg;
Rectangle paddleRect;
float speed = 300.0f;
private OrthographicCamera camera;
private Array<Rectangle> blocks;
private void spawnBlock(int x, int y){
Rectangle block = new Rectangle();
block.x = x*90;
block.y = 400-(y*30);
block.width = 30;
block.height = 10;
blocks.add(block);
}
@Override
public void create() {
Rectangle paddleRect = new Rectangle();
paddleRect.x = 0;
paddleRect.y = 0;
paddleRect.width = 60;
paddleRect.height = 20;
batch = new SpriteBatch();
paddle = new Texture("paddle.png");
blockImg = new Texture("block.png");
camera = new OrthographicCamera();
camera.setToOrtho(false, 400, 400);
blocks = new Array<Rectangle>();
for(int x = 0; x < 5; x++){
for(int y = 0; y < 4; y++){
spawnBlock(x, y);
}
}
}
@Override
public void render() {
Gdx.gl.glClearColor(0.5f, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(paddle, paddleRect.x, paddleRect.y);
for(Rectangle block: blocks){
batch.draw(blockImg, block.x, block.y);
}
batch.end();
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
paddleRect.x += speed * Gdx.graphics.getDeltaTime();
else if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
paddleRect.x -= speed * Gdx.graphics.getDeltaTime();
if(Gdx.input.isKeyPressed(Input.Keys.UP))
paddleRect.y += speed * Gdx.graphics.getDeltaTime();
if(paddleRect.x < 0f)
paddleRect.x = 0f;
if(paddleRect.x > 340f)
paddleRect.x = 340f;
Iterator<Rectangle> iter = blocks.iterator();
while(iter.hasNext()){
Rectangle block = iter.next();
if(block.overlaps(paddleRect))
iter.remove();
}
}
}
可能重複[?什麼是空指針異常,以及如何修復它(http://stackoverflow.com/questions/218384/what-is-a-空指針異常和如何-DO-I-FIX-IT) – lukelazarovic