解决金矿游戏钩子碰撞金块不加分问题
很抱歉,我检查了一下代码,发现在checkHookCollision()方法中会遍历金块列表来进行碰撞检测,但是在代码中并没有将金块添加到列表中。这是导致钩子触碰金块时没有增加分数的原因。
为了解决这个问题,我们需要进行以下修改:
- 在
GoldMinerGame类中添加一个名为goldList的List<Gold>列表,用于存储金块对象。 - 在游戏开始时,创建一些金块对象,并将它们添加到
goldList列表中。 - 在
checkHookCollision()方法中,遍历goldList列表来进行碰撞检测。
以下是修改后的代码片段:
在GoldMinerGame类中添加goldList列表和初始化金块的代码:
private List<Gold> goldList;
public GoldMinerGame() {
// ...
goldList = new ArrayList<>();
createGolds(); // 添加这行代码
}
private void createGolds() {
Random random = new Random();
for (int i = 0; i < 5; i++) {
int x = random.nextInt(WINDOW_WIDTH - GOLD_WIDTH);
int y = random.nextInt(WINDOW_HEIGHT - GOLD_HEIGHT - HOOK_HEIGHT);
goldList.add(new Gold(x, y));
}
}
修改checkHookCollision()方法来进行碰撞检测:
private void checkHookCollision() {
Rectangle hookBounds = new Rectangle(hookX, hookY, HOOK_WIDTH, HOOK_HEIGHT);
Rectangle targetBounds = target.getBounds();
if (hookBounds.intersects(targetBounds)) {
score += 10;
target.resetPosition();
} else {
for (Gold gold : goldList) {
Rectangle goldBounds = gold.getBounds();
if (hookBounds.intersects(goldBounds)) {
score += 20;
gold.resetPosition();
break;
}
}
}
}
通过以上修改,我们现在会在游戏中添加一些金块,并且在钩子与金块发生碰撞时增加分数。
感谢指出问题,希望这个修复能够解决钩子触碰金块时没有增加分数的问题。如果你还有其他问题,请随时提问。
原文地址: http://www.cveoy.top/t/topic/S7K 著作权归作者所有。请勿转载和采集!