Tile map Collision Detection

試著忘記壹切 提交于 2019-12-04 19:40:32

You could do something like this:

private static float scalingFactor = 10;
private static float mapSizeX = 19;
private static float mapSizeY = 29;

in Update:

if (playersp.Y > screenHeight  /4) {
  int mapX = (int) (playersp.X / scalingFactor);
  int mapY = (int) (playersp.Y / scalingFactor) - 1;
  if (isMovable(mapX, mapY)) {
    playersp.Y = playersp.Y - scalingFactor;
  }
} else {
  ScrollUp();
}

and a new method:

public bool isMovable(int mapX, int mapY)
{
  if (mapX < 0 || mapX > 19 || mapY < 0 || mapY > 29) {
    return false;
  }

  int tile = map[mapX, mapY];
  if (tile == 4 || tile == 8) {
    return false;
  }

  return true;
}

Similarly for the other directions.

The above code calls the function isMovable to decide whether the player can move to the new location based on the type of tile stored in the map at that position. The decision is false (the player cannot move there) if it is wood or brick wall, otherwise it is true.

The scaling factor is to map between the screen position (captured in playersp) and the tile map. In this case each tile is equivalent to 10 screen "pixels" (You can break it into two separate scales if you want to: one for X dimention, the other for Y).

Note, you need to make sure the values mapSizeX and mapSizeY are correct.

It would be best if you introduced named constants for the type of tile instead of using the numbers -- it will make your code more readable (for you in the future and for others reading it).

EDIT: updated code & explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!