3

所以我正在尝试构建一个横向滚动平台游戏,并使用平铺地图编辑器创建了一张地图。我已经使用我编写的以下类成功地将非平铺对象和平铺加载到我的游戏中:

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

    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_bitmap = self.tmxdata.get_tile_image_by_gid(gid)
                    if tile_bitmap:
                        surface.blit(   
                            tile_bitmap,
                            (x * self.tmxdata.tilewidth, y * self.tmxdata.tileheight),
                        )

            # This doesn't work but I tried to do this

            elif isinstance(layer, pytmx.TiledObject):
                for x, y, gid in layer:
                    for objects in self.tmxdata.objects:
                        if objects.name == "Background":
                            img_bitmap = self.tmxdata.get_tile_image_by_gid(gid)

                            surface.blit(img_bitmap, (objects.x, objects.y))

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

现在我正在尝试加载我的背景图像,根据 Tile Map Editor 文档,我已将其制成一个大的瓷砖对象并放入背景层。但我不知道如何使用 Pytmx 加载平铺对象,我尝试查看源代码,它似乎确实支持平铺对象。我知道这些平铺对象具有 gid 属性,但不确定如何使用该属性加载平铺对象图像。

我是 pygame 和 pytmx 的新手,但不一定是 python 的新手。谢谢!

4

1 回答 1

0

我通过阅读 Pytmx 源代码并进行尝试找到了解决方案。所以这是我用来读取平铺对象的代码。

    for tile_object in self.map.tmxdata.objects:
            if tile_object.name == "Player":
                self.player = Player(self, tile_object.x, tile_object.y)
            if tile_object.name == "Platform":
                TiledPlatform(
                    self,
                    tile_object.x,
                    tile_object.y,
                    tile_object.width,
                    tile_object.height,
                )
            if tile_object.name == "Background":
                self.img_bitmap = self.map.tmxdata.get_tile_image_by_gid(
                    tile_object.gid
                )

                self.temp_rect = pg.Rect(
                    tile_object.x, tile_object.y, tile_object.width, tile_object.height
                )

本质上,循环遍历你的对象,因为这是一个 tile 对象,它有一个 gid 属性。获取带有 gid 的图像,然后我创建了一个矩形,这样我就可以将我的相机应用于背景(以获得视差效果)。然后你blit图像,矩形,然后就可以了。

此外,在渲染我的瓦片地图时,我必须包含一个 pg.SRCALPHA 标志,以使其看起来正确。

于 2020-07-13T18:07:57.327 回答