Saturday, 17 August 2013

Java: Call methods of s class that instantiated this one

Java: Call methods of s class that instantiated this one

I'm developing a game in Java (LWJGL with OpenGL to be specific) and I
encounter a following problem. I want to have an ArrayList of all textures
in an object with the main loop, and access these from objects
instantiated in this main object. A simplified example:
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
}
}
To clarify, in my real code the ResourceLoader has about 20 textures to
load. There is a total of over 400 entities in the game that have a draw
method just like Player.class and most of them share the same texture,
e.g. there is about 150-180 wall object all showing same image of bricks.
The Game object is NOT the main class and it does not have the static void
main(), but it is one of the only few things instantiated in the main()
method of the game;
Also in the past I have been going around the problem by letting each
entity load it's own texture file, but as I increase the complexity and
map size, it becomes very inefficient to load same image hundreds of
times.
I arrived at the state of the code above from answer here:Calling outer
class function from inner class but I believe I would have to put
ResourceLoader.class and Player.class inside the game.class, which would
not be good considering there are about 20 files that need this treatment,
most are 200+ lines long.
I think my Texture object as well as initialization of OpenGL and other
stuff are pretty generic and should not impact the issue in question, but
I can provide these if necessary.
Thank you for your time and help
~ Kris

No comments:

Post a Comment