gpt4 book ai didi

java - 让玩家仅落在平台上

转载 作者:行者123 更新时间:2023-12-01 09:29:31 25 4
gpt4 key购买 nike

我正在尝试创建一个 2D 平台游戏,并且即将尝试实现跳跃。然而,我对如何让玩家只落在平台上有点迷失。

我正在考虑创建一个名为 Platform 的新类,然后创建一个包含游戏中所有平台的所有坐标的 ArrayList。

然后我创建一个 while 循环,每当玩家跳跃时,当他下落时,除非他站在平台上,否则它会继续下落?

类似于:

while(// This is where you check if the player's y coordinate is above all of the platforms in the game, so WHILE you are above all of the platforms, continue falling.){

playery--;
repaint();
// Some kind of wait here
}

我在这里采取的方法正确吗?我是否把事情复杂化了?有没有更简单的方法来实现这一目标?

最佳答案

通常你的玩家对象中有一个 update() 和 render() 方法。为了方便重力,您可以在每次更新调用时更新玩家的 y 位置,例如posY+=5。对于高级重力,您可以使用 y 速度来更新 y 位置每次更新。此 y 速度会发生变化,以使运动更加平滑。

您应该有一个 Controller 类,它将游戏中的每个实体保存在某个集合中。在我的游戏中,这个类称为 EntityManager,它保存 LinkedList 中的每个实体。我建议为不同的实体类型建立多个集合。在这种情况下,您可以使用 BlockEntities 来表示构成平台的方形 block 。

现在是最重要的概念。每个实体都有一个返回矩形对象作为碰撞盒的方法。这是我制作的游戏的示例:

 public Rectangle getBounds() {
return new Rectangle( x, y, width, height);
}

x、y、宽度和高度是实体的属性。

此外,您的播放器需要一个位于播放器底部的碰撞箱。例如,如果玩家尺寸为 32x32 像素:

 public Rectangle getBottomBounds() {
return new Rectangle( x, y+30, width, 2);
}

现在是碰撞控制:在你的播放器中,你需要一个像这样的字段:

    protected LinkedList<Block> blocks = null;

在您的播放器中实现此方法:

public void checkBottomCollision() {
blocks = game.getEntityManager().getBlocks();
for (int i = 0; i < blocks.size(); i++) {
Block tempBlock = blocks.get(i);
if(this.getBottomBounds().intersects(tempBlock.getBounds())){
this.y = tempBlock.getY() + this.height;
}
}
}
}

game.getEntityManager() 获取包含游戏中所有实体的 ControllerClass。 getBlocks() 方法返回包含所有 block 的 LinkedList。您检查玩家是否对每个方 block 发生碰撞。如果底部命中框发生碰撞,您将更新位置,以便您的玩家站在方 block 上。更新 y 位置后,您可以在 update-method 中调用此方法。

玩得开心;-)

关于java - 让玩家仅落在平台上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com