首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Pytmx处理瓦片对象

使用Pytmx处理瓦片对象
EN

Stack Overflow用户
提问于 2020-07-13 03:28:19
回答 1查看 378关注 0票数 3

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

代码语言:javascript
复制
 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

现在我正在尝试加载我的背景图像,根据瓦片地图编辑器文档,我已经制作成一个大瓦片对象并放在背景层中。但我不知道如何使用Pytmx加载平铺对象,我试着查看了源代码,它似乎确实支持平铺对象。我知道这些磁贴对象有一个gid属性,但不确定如何使用它加载磁贴对象图像。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-14 02:07:57

我通过阅读Pytmx源代码并尝试各种方法找到了解决方案。这是我用来读取瓦片对象的代码。

代码语言:javascript
复制
    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标志,以便它看起来正确。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62865612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档