我的代码是无效还是需要垃圾收集器?

时间:2015-11-02 16:54:00

标签: libgdx

不知道你是否被允许在这里问这个问题,但是我想知道我的代码是否效率低下并且给垃圾收集器留下了很多工作,因为我试图找到一个我游戏中的滞后来源。

这是通过json文件加载世界的类。

Worldloader.java:

package com.Sidescroll.game.Helpers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.Sidescroll.game.GameObjects.Background;
import com.Sidescroll.game.GameObjects.Platform;
import com.Sidescroll.game.GameObjects.Player;
import com.Sidescroll.game.GameWorld.GameWorld;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;

public final class WorldLoader {

    private WorldLoader() {}

    public static HashMap<String, GameWorld> worlds = new HashMap<String, GameWorld>();

    private static JsonValue jsonPlatforms, jsonSpawn, jsonBackgrounds;

    public static GameWorld loadWorld(String levelName) {
        if(worlds.get(levelName) != null) return worlds.get(levelName);

        //load json file
        FileHandle handle = Gdx.files.internal("levels/" + levelName + ".json");
        String fileContent = handle.readString();
        JsonValue json = new JsonReader().parse(fileContent);

        jsonPlatforms = json.get("platforms");
        jsonBackgrounds = json.get("backgrounds");
        jsonSpawn = json.get("spawn");

        //loads platforms
        List<Platform> platforms = new ArrayList<Platform>();
        for(JsonValue pValue : jsonPlatforms.iterator()) {
            Platform platform = new Platform(pValue.getInt("x"),
                                        pValue.getInt("y"),
                                        pValue.getInt("width"),
                                        pValue.getInt("height"),
                                        Platform.Type.valueOf(Platform.Type.class, pValue.getString("type")),
                                        pValue.getString("variant"));
            platforms.add(platform);
        }

        //create player
        Vector2 vecSpawn = new Vector2(jsonSpawn.getInt("x"), jsonSpawn.getInt("y"));
        Player player = new Player(vecSpawn, platforms);

        //loads backgrounds
        List<Background> backgrounds = new ArrayList<Background>();
        for(JsonValue bgValue : jsonBackgrounds.iterator()) {
            Background bg = new Background("bin/sprites/" + bgValue.getString("name") + ".png",
                                            bgValue.getInt("x"),
                                            bgValue.getInt("y"),
                                            bgValue.getInt("width"),
                                            bgValue.getInt("height"),
                                            bgValue.getBoolean("front"));
            backgrounds.add(bg);
        }

        worlds.put(levelName, new GameWorld(player, platforms, backgrounds));
        return worlds.get(levelName);
    }
}

0 个答案:

没有答案