问题:我已经开始尝试创建一个自定义的tile引擎来进行练习。然而,在大门外,我遇到了一个问题。如果有人能仔细阅读下面的所有内容,并至少为我指明正确的方向,我将不胜感激。
目标:Tile类在其构造函数中使用一个字符串作为参数,该参数是从存储在assets文件夹中的.PNG文件的字符串数组中给定的。然后,它被用来创建一个精灵,然后我尝试将其渲染到屏幕上。
故障排除完成:
1) 我已经使用了断点来遍历代码,并且在到达初始化它的代码后,没有发现任何签出为Null的内容。
2) 我在谷歌上搜索了关于如何在LibGdx中创建精灵和使用纹理的教程,据我所知,我做得很正确。
3) 我已经阅读了LibGdx文档,看看这个过程中是否有我不理解的地方,我在这里所做的似乎没有任何问题。
4) 我在这里阅读了不同的NullPointer相关问题,看看我是否也在做什么,没有发现任何类似或接近我在这里做的事情。
发生了什么:这是日志的图片:记录
这是Tile类和TileMap类:
瓷砖类别:
package com.tilemap.saphiric;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
/**
* Base Tile Class for TileMap generation
*/
public class Tile extends Sprite{
protected Texture texture;
protected Sprite sprite;
public Tile(String texture){
this.texture = new Texture(texture);
this.sprite = new Sprite(this.texture);
}
@Override
public void setPosition(float x, float y) {
super.setPosition(x, y);
}
@Override
public float getX() {
return super.getX();
}
@Override
public float getY() {
return super.getY();
}
}
TileMap类:
package com.tilemap.saphiric;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class TileMap extends ApplicationAdapter {
private String[] mTextures = new String[4];
SpriteBatch batch;
Tile water;
@Override
public void create () {
// Runs setup method to create texture array
setup(1);
batch = new SpriteBatch();
water = new Tile(mTextures[3]);
System.out.print(String.valueOf(water.texture));
water.setPosition(Gdx.graphics.getWidth()/2 - water.getWidth()/2,
Gdx.graphics.getHeight()/2 - water.getHeight()/2);
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(water, water.getX(), water.getY());
batch.end();
}
// This method recursively initializes the mTextures array with the necessary assets, called on creation
private int setup(int runCount){
// Initializes the texture array for tile creation
mTextures[0] = "dirt_tile.png";
mTextures[1] = "grass_tile.png";
mTextures[2] = "stone_tile.png";
mTextures[3] = "water_tile.png";
runCount --;
if(runCount == 0){
return 0;
}
return setup(runCount);
}
}
问题是您的Tile
需要用Texture
初始化。引用Sprite
代码文档:
[默认构造函数]创建一个未初始化的精灵精灵在绘制之前需要设置纹理区域和边界
换句话说,Tile
构造函数需要调用它的超类Sprite
,用Texture
或TextureRegion
初始化它。这应该有效:
public Tile(String texture){
super(new Texture(texture));
}