Java 如何制作一个hitbox?

Java 如何制作一个hitbox?,java,Java,我正在制作一个类似于马里奥的游戏,我用数组和图像生成了这个地图。但我的问题是,我不知道如何为所有的瓷砖制作一个hitbox系统。我试着根据你在地图上的位置建立一个基于位置的碰撞系统 像这样 if(xpos > 10*mapX && xpos < 14 * mapX){ ypos -= 1; } if(xpos>10*mapX&&xpos

我正在制作一个类似于马里奥的游戏,我用数组和图像生成了这个地图。但我的问题是,我不知道如何为所有的瓷砖制作一个hitbox系统。我试着根据你在地图上的位置建立一个基于位置的碰撞系统

像这样

if(xpos > 10*mapX && xpos < 14 * mapX){
    ypos -= 1;
}
if(xpos>10*mapX&&xpos<14*mapX){
ypos-=1;
}
但我不想对每一堵墙或每一个洞都这样。 那么,有没有一种方法可以检查角色的前面、下面和上面,看看是否有一个点击框,如果有,你就不能移动那个方向或者摔倒


谢谢你

如果这是一个简单的2D游戏,我建议你把地图分成方块。您可以将地图作为二维数组存储在内存中,并在每个帧期间检查播放器附近的分幅。当然,在移动过程中,他可以占据多达4个瓷砖,但这让你只能检查多达12个位置,这很容易做到

使用图像位置和尺寸可以轻松地进行进一步的碰撞检查

请记住,无需检查静态对象(环境)是否与某物发生碰撞,只需检查自上一帧开始移动的对象,即播放器和精灵

编辑:

假设您得到了映射的以下部分(变量映射):

在哪里

您还有一对
(x,y)
表示播放器的平铺索引(不是确切位置)。在这种情况下,您必须执行以下操作:

if ("o".equals(map[y + 1, x + 1]))
//floor is under
if ("e".equals(map[y, x + 1]))
//enemy is on the right
if ("o".equals(map[y - 1, x]))
//floor is above us

如果满足这些条件中的任何一个,您必须检查图像位置并处理冲突。

注意:在上一篇文章发表后单击提交方式

正如Mateusz所说,2D阵列最适合这种类型的游戏:

e、 g.使用字符:

 0123456789012
0           ==
1        * ===
2===== =======
因此,在本例中,tileMap[8][1]=='*'。您可能最好使用枚举而不是字符,例如,对于Sonic样式的弹簧板,使用Tile.SPRING

如果您的地图由常规大小的瓷砖组成,您可以说:

int xInFrontOfPlayer = playerX + PLAYER_WIDTH;
int xBehindPlayer = playerX - PLAYER_WIDTH;

Tile tileInFrontOfPlayer = getTileAtWorldCoord(xInFrontOfPlayer, playerY);
Tile tileBehindPlayer = getTileAtWorldCoord(xBehindPlayer, playerY);

...

public Tile getTileAtWorldCoord(int worldX, worldY) {
    return tileMap[worldX / TILE_WIDTH][worldY / TILE_HEIGHT];
}
其中,平铺宽度和平铺高度是平铺的尺寸(以像素为单位)。然后对yAbovePlayer和yBelowPlayer使用类似的数学

然后,您的游戏循环中可能会有一些逻辑:

if user is pressing the "go right" key:
      if the tile to the right is Tile.SPACE:
            move player right
      else if the tile to the right is Tile.WALL:
            don't do anything

if the tile below is Tile.SPACE:
    fall

但是你如何检查角色的前面和下面是否有什么东西呢;但我相信你应该评估dyn4j()
int xInFrontOfPlayer = playerX + PLAYER_WIDTH;
int xBehindPlayer = playerX - PLAYER_WIDTH;

Tile tileInFrontOfPlayer = getTileAtWorldCoord(xInFrontOfPlayer, playerY);
Tile tileBehindPlayer = getTileAtWorldCoord(xBehindPlayer, playerY);

...

public Tile getTileAtWorldCoord(int worldX, worldY) {
    return tileMap[worldX / TILE_WIDTH][worldY / TILE_HEIGHT];
}
if user is pressing the "go right" key:
      if the tile to the right is Tile.SPACE:
            move player right
      else if the tile to the right is Tile.WALL:
            don't do anything

if the tile below is Tile.SPACE:
    fall