首页 > 解决方案 > 在 PyTMX 和 PyGame 中将微小的 TileMap 缩放到更大的尺寸

问题描述

所以我设法在我的 PyGame 项目中创建、导入和显示 16x16 TileMap。我有一个名为ground的资产层和一个最初称为objects的 Objects 层。

带有我的图层的平铺软件屏幕截图

然后我有这个简单的代码来创建我的 TileMap :

class TiledMap:
def __init__(self, filename):
    tm = pytmx.load_pygame(filename, pixelalpha=True)
    self.width = tm.width * TILE_SIZE
    self.height = tm.height * TILE_SIZE
    self.tmxdata = tm

def render(self, surface):
    ti = self.tmxdata.get_tile_image_by_gid
    for layer in self.tmxdata.visible_layers:
        if isinstance(layer, pytmx.TiledTileLayer):
            for x, y, gid, in layer:
                tile = ti(gid)
                if tile:
                    tile = pg.transform.scale(tile,(TILE_SIZE,TILE_SIZE))
                    surface.blit(tile, (x * TILE_SIZE,
                                        y * TILE_SIZE))

def make_map(self):
    temp_surface = pg.Surface((self.width, self.height), pg.SRCALPHA).convert_alpha()
    self.render(temp_surface)
    return temp_surface

编辑:我忘了说我的 16x16 地图实际上已重新缩放为 64x64 (TILE_SIZE) 图像,但仅适用于可见层ground,我也想对对象层进行此操作。

这对于缩放我的地面“可见层”非常有用。但是当我绘制碰撞时,您可以看到对象仍然非常小并且不适合我的新地图分辨率:

Blue:Player hit box 和 Yellow:Colliders 的游戏截图

如您所见,我在 TileMap 中设置的墙壁的命中框未正确缩放。

所以问题是,如何使用 pyTMX 缩放 TileMap 的对象层?

谢谢你们。

标签: python-3.xpygamepytmx

解决方案


所以我找到了一种纠正方法,我不知道这是否是最干净的方法,但这里是解决方案代码:

def new(self):
    # Initialization and setup for a new game
    self.all_sprites = pg.sprite.LayeredUpdates()
    self.walls = pg.sprite.Group()
    self.items = pg.sprite.Group()

    for tile_object in self.map.tmxdata.objects:

        tile_object.x *= int(TILE_SIZE / self.map.tilesize)
        tile_object.y *= int(TILE_SIZE / self.map.tilesize)

        obj_center = vec(tile_object.x + tile_object.width / 2,
                         tile_object.y + tile_object.height / 2)

        if tile_object.name == 'player':
            self.player = Player(self, obj_center.x, obj_center.y)

        elif tile_object.name in ['pickaxe']:
            Item(self, obj_center, tile_object.name)

        else:
            tile_object.width *= int(TILE_SIZE / self.map.tilesize)
            tile_object.height *= int(TILE_SIZE / self.map.tilesize)

        # if tile_object.name == 'zombie':
        #     Mob(self, tile_object.x, tile_object.y)

        if tile_object.name == 'wall':
            Obstacle(self, tile_object.x, tile_object.y, tile_object.width, tile_object.height)


    self.camera = Camera(self.map.width, self.map.height)
    self.paused = False
    self.draw_debug = False

因此,在我的game.new()函数中,我通过解析 spritesheet 来检索玩家和对象的精灵,并且我已经将它们缩放到正确的大小。但是对于其他实体的大小和位置,更正只是将值乘以正确的数字。作为比例因子的数字:16x16 到 64x64 瓦片集给出 64/16,即 4。

所以我只需将实体 x、y、宽度和高度乘以 4。

希望它无论如何都会对某人有所帮助。


推荐阅读