簡體   English   中英

在libgdx中繪制精靈

[英]Drawing sprites in libgdx

我打電話時得到了NullPoinerExecption

enemy.getSprite().draw(batch);

我必須在哪里初始化我的精靈? 它在主類中起作用,但是如果我嘗試在Enemy構造函數中初始化紋理和子畫面,則會給我錯誤。

這是我的主要課程

  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();
        }

敵人階級

 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);
    }

您從未在Enemy實例上調用過create() ,因此Enemy中的紋理和精靈不會被實例化。 create()方法中調用enemy.create() 或簡化事情,然后將敵人enemy.create()的代碼enemy.create() Enemy構造函數中。

同樣,在您的Enemy構造函數中,您將實例化一個無用的Sprite實例,該實例不引用Texture,一旦對敵人調用create() ,該實例將被丟棄。 而且構造函數甚至不使用傳入的Sprite引用(盡管您現在無論如何都只是傳入null ,因為spriteEnemy類中的spriteEnemy從未實例化)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM