python-3.x - 在 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 的对象层?
谢谢你们。
解决方案
所以我找到了一种纠正方法,我不知道这是否是最干净的方法,但这里是解决方案代码:
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。
希望它无论如何都会对某人有所帮助。
推荐阅读
- jquery - 在 Google Chrome 中更改 GIF 图片 src 会使图片卡顿
- python-3.x - 如何使用 Selenium 获取 html 代码中的文本?
- laravel - 我想将数据从一个视图发送到另一个 Laravel 视图
- javascript - How to select a specific row from some same class name of a table using jQuery
- java - 如何在 Java 中获取属性的所有者类?
- java - 如何在 .dxf 中为 Groupcode 1001 获取/设置应用程序名称?
- dax - DAX IF 度量 - 返回固定值
- javascript - 不使用分组运算符立即调用函数表达式
- prometheus - 在 Prometheus 警报规则中验证不同实例上的某些指标
- c# - 使用 Linq 将对象字段选择到地图中