调用实例化此类的类的方法

时间:2013-08-17 22:31:36

标签: java methods inner-classes outer-classes resource-loading

我正在开发一个使用轻量级Java游戏库(LWJGL)和OpenGL的Java游戏。

我遇到了以下问题。

我想在主循环中的对象中创建所有纹理的ArrayList,并从在此主对象中实例化的对象中访问它们。一个简化的例子:

game.class:

public class Game {

  ArrayList Textures; // to hold the Texture object I created
  Player player; // create Player object

  public Game() {
    new ResourceLoader(); // Here is the instance of the ResourceLoader class
    player = new Player(StartingPosition) // And an instance of the playey, there are many more arguments I give it, but none of this matter (or so I hope)

    while(true) { // main loop
      // input handlers

      player.draw() // here I call the player charcter to be drawn

    }
  }

  // this method SHOULD allow the resource loader to add new textures
  public void addTextures (Texture tx) {
    Textures.add(tx);
  }
}

ResourceLoader.class

public class ResourceLoader {
  public ResourceLoader() {
    Interface.this.addTexture(new Texture("image.png")); // this is the line I need help with
  }
}

Player.class

public class Player {
  public player() {
    // some stuff, including assignment of appropriate textureID
  }

  public void draw() {
    Interface.this.Textures.get(this.textureID).bind(); // this also doesn't work
    // OpenGL method to draw the character
  }
}

在我的真实代码中,ResourceLoader类有大约20个要加载的纹理。

游戏中总共有超过400个实体具有与Player.class类似的绘制方法,并且大多数实体共享相同的纹理;例如大约有150-180个墙体对象都显示出相同的砖块图像。

Game对象不是主类,它没有static void main()方法,但它是游戏main()方法中实例化的少数事物之一。

此外,在过去,我通过让每个实体加载自己的纹理文件来解决这个问题。但随着我增加复杂性和地图大小,将相同的图像加载数百次变得非常低效。

我从this回答了上面代码的状态。

我相信我必须将ResourceLoader.classPlayer.class放在game.class内,考虑到大约有20个文件需要这种处理并且大部分都是它们长达200多行。

我认为我的Texture对象以及OpenGL和其他东西的初始化非常通用,不应该影响相关问题。如有必要,我可以提供这些。

1 个答案:

答案 0 :(得分:1)

使“外部”类实例成为构造函数的参数:

public class Player {
   final Interface obj;

   public player(Interface obj) {
       this.obj = obj;
      // some stuff, including assignment of appropriate textureID
   }

   public void draw() {
       obj.Textures.get(this.textureID).bind();
   }
}

public class ResourceLoader {
   public ResourceLoader(Interface obj) {
      obj.addTexture(new Texture("image.png"));
   }
}

并在Game中实例化那些:

new Player(this);

注意:使用Interface的示例行但Game没有实现它。我认为这是为发布清理的代码工件。只需使用适合您情况的类型。

相关问题