问题: 我已经开始尝试创建一个用于练习目的的自定义图 block 引擎。然而,一出门我就遇到了问题。如果有人可以阅读下面的所有内容并至少指出我正确的方向,我将不胜感激。
目标: Tile 类在其构造函数中采用一个字符串作为参数,该字符串是从存储在 asset 文件夹中的 .PNG 文件的字符串数组中给出的。然后用它来创建一个 Sprite ,然后我尝试将其渲染到屏幕上。
故障排除完成:
1) 我使用断点单步执行代码,但在到达初始化代码后,没有发现任何检查为 Null 的内容。
2)我在 Google 上搜索了有关如何在 LibGdx 中创建 Sprite 和使用纹理的教程,据我所知,我做得正确。
3)我已经阅读了 LibGdx 文档,看看是否有任何我对这个过程不理解的地方,而且我在这里所做的事情似乎没有任何问题。
4)我在这里阅读了不同的 NullPointer 相关问题,看看是否有任何我正在做的事情跳出来,但没有找到任何与我在这里所做的类似或接近的事情。
发生了什么: 这是日志的图片: Log
这是 Tile 类和 TileMap 类:
图 block 类:
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
code documentation :
[the default constructor] Creates an uninitialized sprite. The sprite will need a texture region and bounds set before it can be drawn.
换句话说,您的 Tile
构造函数需要调用其父类(super class) Sprite
,该类使用 Texture
或 TextureRegion
对其进行初始化。这应该有效:
public Tile(String texture){
super(new Texture(texture));
}
关于java - LibGdx 自定义平铺类 NullPointer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453774/