简体   繁体   中英

Drawing sprites in libgdx

I get a NullPoinerExecption when calling

enemy.getSprite().draw(batch);

Where do I have to initialize my sprite? It works in main class, but if I try to initialize texture and sprite in Enemy constructor then it gives me error.

Here's my main class :

  public class SpaceShooter implements ApplicationListener {

     private SpriteBatch batch;
        private Texture texture;
        private Sprite sprite, spriteEnemy;
        private Player p;
        private Enemy enemy;

        @Override
        public void create() {       
            p = new Player();
            enemy = new Enemy(spriteEnemy);


            float w = Gdx.graphics.getWidth();
            float h = Gdx.graphics.getHeight();

            batch = new SpriteBatch();

            texture = new Texture(Gdx.files.internal("craft.png"));
            sprite = new Sprite(texture);
            sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);

            // Adding enemy sprite

        }

        @Override
        public void dispose() {
            batch.dispose();
            texture.dispose();
        }

        @Override
        public void render() {        
            Gdx.gl.glClearColor(1, 1, 1, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            // moving sprite left and right


            batch.begin();
            sprite.draw(batch);
            enemy.getSprite().draw(batch);          
            batch.end();
        }

Enemy class

 public class Enemy {

    private Sprite sprite;
    private Texture texture;


    boolean gameOver;

    public Enemy(Sprite sprite){

        this.sprite = new Sprite();

    }

    public Sprite getSprite(){
        return sprite;
    }

    public void create() {
        texture = new Texture(Gdx.files.internal("enemy.png"));
        sprite = new Sprite(texture);
        this.sprite.setPosition(100, 200);
    }

You never called create() on your Enemy instance, so the texture and sprite in Enemy are never instantiated. Call enemy.create() in your create() method. Or simplify things and move the code in enemy.create() into the Enemy constructor.

Also, in your Enemy constructor, you are instantiating a useless Sprite instance that does not reference a Texture and which will be thrown away once create() is called on the enemy. And the constructor does not even use the Sprite reference that's passed in (although you are currently just passing in null anyway because spriteEnemy in the SpaceShooter class is never instantiated).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM