【问题标题】:Using a value from json file in Libgdx在 Libgdx 中使用 json 文件中的值
【发布时间】:2016-01-31 12:25:45
【问题描述】:

我想使用 json 文件中的值

这是 Json 文件

{
  "button" : [
    {
      "x" : 50.0
    },
    {
      "x" : 150.0
    }
]
}

我有以下课程

(按钮类)

public class Button extends Sprite{

    float x;

    public Button() {
        super(new Texture("button.png"));
    }

    @Override
    public void setX(float x) {
        this.x = x;
    }

}

(数据类)

public class Data {

    public Array<Button> buttons;

    public void load() {
        buttons = new Array<Button>();

        Json json = new Json();
        json.setTypeName(null);
        json.setUsePrototypes(false);
        json.setIgnoreUnknownFields(true);
        json.setOutputType(JsonWriter.OutputType.json);
        json.fromJson(Data.class, Gdx.files.internal("buttons.json"));

    }
}

(主类)

public class GameMain extends ApplicationAdapter {

    SpriteBatch batch;
    Data data;

    @Override
    public void create () {
        batch = new SpriteBatch();

        data = new Data();
        data.load();

        for(Button b : data.buttons) {
            b.setX(b.x);
        }

    }

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

        batch.begin();
        for(Button b : data.buttons) {
            b.draw(batch);
        }
        batch.end();
    }
}

我想在 json 文件中的特定 x 位置绘制按钮 但它什么也没给我。

我的代码有什么问题?

有什么想法吗?

【问题讨论】:

  • 你应该回去接受关于你旧问题的好答案。你会得到一些代表,人们会更愿意帮助你。

标签: android json libgdx


【解决方案1】:

在 load() 结束时,您还没有分配结果。只需添加按钮 =:

public void load() {
    //instead of this line:
    //buttons = new Array<Button>();

    Json json = new Json();
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setIgnoreUnknownFields(true);
    json.setOutputType(JsonWriter.OutputType.json);
    // set buttons here:
    buttons = json.fromJson(Data.class, Gdx.files.internal("buttons.json"));

}

【讨论】:

  • 你的意思是这个buttons = json.fromJson(Array.class, Gdx.files.internal("buttons.json"));
  • 查看我的编辑。不需要本地按钮,所以按钮就是 this.buttons
【解决方案2】:

您的 Data 类会加载 Data 类的另一个实例,但不会将其分配给任何东西。它是循环的,没有意义。 load 方法应该是静态的,返回一个 Data 对象(这是您当前 load 方法的最后一行所提供的),而不是试图实例化一个未使用的空 buttons 数组。

您的按钮类隐藏了超类的x 字段和setX 方法,因此无法更改绘制时使用的精灵的实际X 位置。 Sprite 已经有一个x 参数,因此您不应该添加自己的参数。如果您只是从 Button 类中删除这两个东西,它应该可以工作。

也就是说,您不应该为每个按钮加载相同纹理的另一个副本。这是对内存和纹理交换的浪费。除非你非常小心地处理这些精灵“拥有”的纹理,否则你也会泄漏内存。

【讨论】:

    猜你喜欢
    • 2013-11-01
    • 2019-10-12
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多