简体   繁体   中英

Java and libgdx: How can I use this variable in two overridden methods?

I am having a big problem trying to figure out how to use a variable in one overridden method, and also use it in another. Specifically, I am using libgdx, and want to use the variable map in the create method in the render method.

Here is my code:

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

    background = new TextureAtlas(
            Gdx.files.internal("data/background/background.pack"),
            Gdx.files.internal("data/background/"));
    bg = background.findRegion("Background");

    t = TMXLoader.readTMX("data/world/World.tmx");

    ArrayList<Image> map = TMXLoader.drawMap();



    camera = new OrthographicCamera(WIDTH, HEIGHT);
    camera.position.set(WIDTH / 2, HEIGHT / 2, 0);
    camera.update();
}

@Override
public void render() {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    BufferedImage image = new BufferedImage(20, 20,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D) image.getGraphics();

    batch.begin();
    for (int i = 0; i < WIDTH; i += bg.getRegionWidth()) {
        for (int j = 0; j < HEIGHT; j += bg.getRegionHeight()) {
            batch.draw(bg, i, j);
        }
    }

    for (int x = 0; x < t.width; x++) {
        for (int y = 0; y < t.height; y++) {
            for (Image tile : map) {
                float[] scale = getScale();

                Image scaledTile = tile.getScaledInstance(
                        (int) (t.tilewidth * scale[0]),
                        (int) (t.tileheight * scale[1]), Image.SCALE_FAST);
                g2d.drawImage(scaledTile, x, y, null);
            }
        }
    }
    batch.end();
}

As it is, I can't access map in the render method. I can't create my own method, because it would have to be called in each method create and render. I am stuck, and can't figure it out on my own. I have a feeling I could use a get/set to do this, but I'm not quite sure how I'd try to do that...

Declare map as a global variable.

private ArrayList<Image> map;

Inside create method, do the assignment as you did-

map = TMXLoader.drawMap();

Now in render method, you can use the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM