我正在用 Java 开发一款游戏,它使用带有 OpenGL 的轻量级 Java 游戏库 (LWJGL)。
我遇到了以下问题。
我想在主循环中创建一个对象中所有纹理的 ArrayList,并从此主对象中实例化的对象访问这些纹理。一个简化的例子:
游戏类:
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 个墙对象都显示相同的砖 block 图像。
Game
对象不是主类,它没有 static void main()
方法,但它是在main()
游戏的方法。
另外,在过去,我通过让每个实体加载自己的纹理文件来解决这个问题。但是随着我增加复杂性和 map 大小,加载同一张图像数百次变得非常低效。
我从 this 到达上面代码的状态回答。
我相信我必须将 ResourceLoader.class
和 Player.class
放在 game.class
中,这不是一个好主意解决方案考虑到大约有 20 个文件需要这种处理,其中大多数文件的长度超过 200 行。
我认为我的 Texture
对象以及 OpenGL 和其他东西的初始化非常通用,不应影响所讨论的问题。如果需要,我可以提供这些。
最佳答案
使“外部”类实例成为构造函数的参数:
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
没有实现它。我假设这是为发布而清理的代码工件。只需使用适合您情况的类型即可。
关于java - 调用实例化该类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18293901/