以下方案:
类:

GamePlayScene(游戏逻辑和碰撞检测)
障碍(具有Rect getObstacleBounds()方法以返回Bounds)
ObstacleManager(具有障碍物对象的LinkedList)

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

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

因此,我认为我还必须在我的障碍管理器中实现Rect getObstacleBounds(),从中循环遍历List中的每个障碍并返回该Rect。

这是正确的方法吗?我对在LinkedList中访问对象及其方法还很陌生

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

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

GameScene.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
}


障碍物

//...
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的列表并检查是否发生了任何匹配

GameScene.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来检查障碍物是否被击中):

GameScene.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;
}


有几种方法可以实现您想要的。最后,取决于您要确切执行的操作。

07-26 08:16