私は、Java でモンスターと衝突するレーザーのバウンディング ボックス衝突に取り組んでいます。衝突しても問題ありません。問題は、OneEye クラス内の Rectangle オブジェクトが静的であることです!
問題 1: ゲーム内に 1 つのモンスターが存在する場合は問題ありませんが、私のゲームではモンスター クラスのインスタンスを多数追加します。したがって、複数のモンスターを追加する場合、Rectangle オブジェクトを静的にすることはできません。
問題 2: 注: Rectangle オブジェクトが非静的である場合、Rectangle の getter メソッドは非静的である必要があります。
しかし、これら2つの問題を解決する方法がわかりません。
繰り返しますが、私の衝突はうまくいきます! 同じクラスの異なるインスタンスを追加するとしたら、それはコード設計上の欠陥です。要約すると、静的コンテキストで参照せずにコードを記述している現在のクラスの別のクラスからインスタンスを参照するにはどうすればよいですか。
レーザー クラスと OneEye クラスの 2 つのクラスのコードを次に示します。
public class Laser {
/* use a bounding box
* to test collision detection
*
*/
private Rectangle rect;
public void update(long milliseconds) {
// surround a bounding box around the laser
rect = new Rectangle((int)position.x,(int)position.y,this.getWidth(),this.getHeight());
// collision against the OneEye monster
if(rect.intersects(OneEye.getRectangle()))
{
Game.getInstance().remove(this);
}
}
public class OneEye {
/*
* use bounding box
* for collision
* detection
*/
private static Rectangle rect;
public void update(long milliseconds) {
// surround a bounding box around the oneEye monster
rect = new Rectangle((int)position.x,(int)position.y,this.getWidth(),this.getHeight());
}
// can be useful for collision detection
public static Rectangle getRectangle()
{
return rect;
}
}