[英]Drawing sprites in libgdx
I get a NullPoinerExecption when calling 我打电话时得到了NullPoinerExecption
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.
它在主类中起作用,但是如果我尝试在Enemy构造函数中初始化纹理和子画面,则会给我错误。
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. 您从未在Enemy实例上调用过
create()
,因此Enemy中的纹理和精灵不会被实例化。 Call enemy.create()
in your create()
method. 在
create()
方法中调用enemy.create()
。 Or simplify things and move the code in enemy.create()
into the Enemy constructor. 或简化事情,然后将敌人
enemy.create()
的代码enemy.create()
Enemy构造函数中。
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. 同样,在您的Enemy构造函数中,您将实例化一个无用的Sprite实例,该实例不引用Texture,一旦对敌人调用
create()
,该实例将被丢弃。 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). 而且构造函数甚至不使用传入的Sprite引用(尽管您现在无论如何都只是传入
null
,因为spriteEnemy
类中的spriteEnemy
从未实例化)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.