如何在 Java 中为 2D 游戏构建平铺地图?
不知道如何解决这个问题.
Not sure how to approach this problem.
基本上,我想要一个 Pixel -> 400x400 窗口的平铺表示.屏幕上的每个坐标,例如 120x300
应该是图块的一部分.我最小的精灵是 4 像素,所以我们可以说 1 块 = 4 像素.玩家和敌人的精灵都是 20 x 20,所以每个玩家/坏人将占据 5 格.
Basically, I want a Pixel -> Tile representation of a 400x400 window. Each coordinate on the screen, e.g 120x300
should be part of a tile. My smallest sprite is 4 pixels, so we can say that 1 tile = 4 pixels. The player and enemy sprites are all 20 x 20, so each player/bad guy will occupy 5 tiles.
然后我想用这个 Map 类来:
Then I want to use this Map class to:
通过提供图块的索引/id 来检索玩家/怪物精灵的 x/y 坐标.
Retrieve the x/y coordinates of a player/monster sprite by suppling the index/id of the tile.
知道边界在哪里,所以它不会将精灵移动到 400x400
之外,从而隐藏它.
Knowing where the boundaries are, so it doesn't move the sprite beyond 400x400
, thus hiding it.
碰撞检测,知道瓷砖是否空置.
Collision detection, knowing whether a tile is vacant or not.
这是怎么做到的?在这里专门讨论 x,y->tile 或 tile index->x,y 转换(用于适当地绘制精灵).
How can this be done? Talking specifically about the x,y->tile or tile index->x,y conversion (for drawing the sprites appropriately) here.
首先,将只与表示有关的像素与瓦片的概念分开,瓦片是一个实际的游戏对象,在其上施加约束游戏.
Firstly, split out the concept of a pixel, which is just concerned with representation, with a tile, which is an actual game object with constraints it places on the game.
我发现解决此类问题的一个好方法是开始勾勒出您想要的粗略 API.类似的东西:
I find a good way to disentangle things like this is to start out sketching out the rough API of what you want. Something like:
public class Board {
public Board (int width, int height){.. }
public boolean isOccupied(int x, int y){.. }
public void moveTo(Point from, Point to) { ..
(maybe throws an exception for outofbounds )
电路板的所有内部单位都在瓦片中,而不是像素.然后像素信息可以从棋盘上独立地从瓦片表示中通过一点内部乘法导出-
where all internal units of the board are in tiles, not pixels. Then pixel information can be derived from the board independantly from the tile representation with a bit of internal multiplication-
public Point getPixelPosition(int xTilePos, int yTilePos, int pixelsPerTile)..
瓷砖可以在内部表示为二维数组或单个数组,在这种情况下,您将使用某种内部表示方案将您的数组映射到棋盘方块,从而进行 mod 算法.
The tiles can be internally represented as a 2d array or a single array, in which case you'd use some kind of internal representation scheme to map your array to the board squares, thus the mod arithmetic.