2

OpenGL で軽量 Java ゲーム ライブラリ (LWJGL) を使用する Java でゲームを開発しています。

次の問題が発生しました。

メイン ループ内のオブジェクト内のすべてのテクスチャの 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 の壁オブジェクトがすべて同じレンガのイメージを示しています。

Gameオブジェクトはメイン クラスではなく、メソッドもありませんが、ゲームstatic void main()のメソッドでインスタンス化される数少ないオブジェクトの1 つです。main()

また、以前は、各エンティティに独自のテクスチャ ファイルをロードさせることで、この問題を回避していました。しかし、複雑さとマップ サイズを増やしていくと、同じ画像を何百回も読み込むのは非常に効率が悪くなります。

この回答から上記のコードの状態にたどり着きました。

この処理が必要なファイルが約 20 個あり、それらのほとんどが 200 行以上の長さであることを考えると、これは良い解決策ではありませんResourceLoader.classPlayer.classgame.class

私のTextureオブジェクトとOpenGLの初期化やその他のものはかなり一般的であり、問​​題に影響を与えるべきではないと思います。必要に応じてこれらを提供できます。

4

1 に答える 1

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);

注: サンプル行は使用されていますが、実装されてInterfaceGameません。これは、投稿のためにクリーンアップされたコードのアーティファクトだと思います。状況に適したタイプを使用してください。

于 2013-08-17T22:37:34.730 に答える