以下方案:
班级:
GamePlayScene (游戏逻辑和碰撞检测)
障碍物(具有Rect getObstacleBounds()方法以返回Bounds)
ObstacleManager (具有障碍物对象的LinkedList)
我想访问障碍物的边界(android.Rect)。所有障碍物都将存储在LinkedList中。
现在在正在运行的游戏中,我想访问我的 GameplayScene类中的getObstacleBounds()方法,但问题是我无法直接访问障碍物,但是显然我必须循环遍历所有对象我的ObstacleManager的LinkedList中的对象。
由于这个原因,我认为我还必须在我的障碍管理器中实现一个Rect getObstacleBounds(),从那里我循环遍历List中的每个障碍并返回该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?
}
答案 0 :(得分:0)
最后,取决于您要在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;
}
有几种方法可以实现您想要的。最后,取决于您要确切执行的操作。