如何从 LinkedList 的对象访问 getter

How to access a getter from an object of a LinkedList

以下场景:
Classes:

GamePlayScene(游戏逻辑和碰撞检测)
Obstacle(具有 return 边界的 Rect getObstacleBounds() 方法)
ObstacleManager(有障碍物对象的LinkedList)

我想访问障碍物的边界(android.Rect)。所有障碍物都将存储到一个 LinkedList 中。

现在在 运行 游戏中,我想在我的 GameplayScene Class 中访问 getObstacleBounds() 方法,但问题是我不能直接访问障碍对象,但显然我必须在我的 ObstacleManager 中循环访问 LinkedList 中的所有对象。

因此,我认为我还必须在我的障碍物管理器中实现一个 Rect getObstacleBounds(),从那里我循环遍历列表中的每个障碍物和 return 那个 Rect。

这样做正确吗?我对在 LinkedList

中访问对象及其方法还很陌生

如果不是:我将如何实现对此类方法的访问?

这是我的想法,我认为冷工作/是正确的方法。 (不可编译,或多或少的伪代码)

GameplayScene.java

private ObstacleManager obstacleManager;

public GameplayScene() {

  obstacleManager = new ObstacleManager();
  obstacleManager.addObstacle(new Obstacle(...));
}

public void hitDetection() {
//get the Boundaries of obstacle(s) for collision detection
}

Obstacle.java

//...
public Rect getObstacleBounds() {
   return obstacleBounds;
}

ObstacleManager.java

LinkedList<Obstacle> obstacles = new LinkedList<>();

public void update() { //example method 
    for (Obstacle o : obstacles){
        o.update();
    }
}

public Rect getObjectBounds() {
   return ...
   //how do I cycle through my objects and return each Bounds Rect?
}

最后,取决于你想在hitDetection

中做什么

如果你只是想检查是否发生了命中

在这种情况下,您可以只接收 Rect 的列表并检查是否有命中发生

GameplayScene.java

public void hitDetection() {
    ArrayList<Rect> listOfBounds = obstacleManager.getObstacleBounds();
    for(Rect bound : listOfBounds) {
        // Do you stuff
        // Note the here, you are receiving a list of Rects only.
        // So, you can only check if a hit happened.. but you can't update the Obstacles because here, you don't have access to them.
        // Nothing stops you of receiving the whole list of items if you want to(like the reference of ObstacleManager.obstacles).
    }
}

ObstacleManager.java

    public ArrayList<Rect> getObjectBounds() {
        // You can also return just an array.. like Rect[] listToReturn etc
        ArrayList<Rect> listToReturn = new ArrayList(obstacles.size());
        for (Obstacle item : obstacles) {
            listToReturn.add(item.getObjectBounds);
        }
        return listToReturn;
    }

如果您需要更新有关被击中的障碍物的一些信息

在这种情况下,您可以将 hitDetection 逻辑传输给您的 ObstacleManager(我假设您检查坐标 X 和 Y 以检查障碍物是否被击中):

GameplayScene.java

public void hitDetection(int touchX, int touchY) {
    Obstacle objectHit = obstacleManager.getObstacleTouched(int touchX, int touchY);
    if (objectHit != null) {
        objectHit.doStuffAlpha();
        objectHit.doStuffBeta();
    } else {
        // No obstacle was hit.. Nothing to do
    }
}

ObstacleManager.java

public Obstacle getObstacleTouched(int touchX, int touchY) {
    Obstacle obstacleToReturn = null;
    for (Obstacle item : obstacles) {
        if(item.wasHit(touchX, touchY) {
            obstacleToReturn = item;
            break;
        }
    }
    return listToReturn;
}

有多种方法可以实现您想要的效果。有些比其他的好等最后,取决于你想做什么。