如何让自定义瓦片系统适配Python的Pygame Sprite精灵系统
问题描述
我正在为游戏开发自定义瓦片系统,这是首次独立实现(未参考教程)。使用blit方法渲染瓦片时功能正常,但使用pygame.sprite.Sprite精灵组件时无法正常工作。由于精灵系统能简化后续开发操作,我需要让瓦片系统适配该系统,推测是入门级错误但暂未定位到问题。
相关代码:
# Importing libraries try: import pygame from pygame.locals import * from time import * from os import * from random import * import sys print("All Libraries imported successfully \n") except : print("Error while importing modules and libraries") sys.exit() # Creating Screen screen_width = 640 screen_height = 640 tile_size = int(screen_width / 10) screen_res = (screen_width, screen_height) clock = pygame.time.Clock() running_fps = 144 screen = pygame.display.set_mode(screen_res) pygame.display.set_caption(f"GTA Circuit Hack FPS:{running_fps}, {screen_width} x {screen_height}, Tile Size: {tile_size}") # Loading images # Background image: backgroundImg = pygame.image.load("Background.png") backgroundImg = pygame.transform.scale(backgroundImg, screen_res) # Not walkable tile image: noWalkTileImg = pygame.image.load("unwalkTile.png") noWalkTileImg = pygame.transform.scale(noWalkTileImg, (tile_size, tile_size)) # making tiles tiles = [] tile_y = 0 tile_x = 0 for i in range(10): if i > 0: tile_y += tile_size for i in range(10): if i > 0: tile_x += tile_size tiles.append((tile_x, tile_y)) tile_x = 0 tile_x = 0 tile_y = 0 # creating object classes class BadTile (pygame.sprite.Sprite): def __init__(self, tile): pygame.sprite.Sprite.__init__(self) self.image = noWalkTileImg self.tile = tile self.rect = self.image.get_rect() self.x = self.tile[0] self.y = self.tile[1] def update(self): self.x = self.tile[0] self.y = self.tile[1] # creating objects tile1 = BadTile(tiles[99]) game_tiles = pygame.sprite.Group() game_tiles.add(tile1) run = True while run: clock.tick(running_fps) screen.blit(backgroundImg, (0,0)) # rendering game_tiles.update() game_tiles.draw(screen) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.update() pygame.quit() print ("Exited with no errors") sys.exit()
使用的图片:

解决方法
问题核心是Pygame精灵的渲染位置由rect属性决定,你在代码里单独定义了x和y但没有同步到rect上,导致精灵无法被正确定位绘制。
修改BadTile类如下:
class BadTile (pygame.sprite.Sprite): def __init__(self, tile): pygame.sprite.Sprite.__init__(self) self.image = noWalkTileImg self.tile = tile # 直接将rect的左上角定位到目标瓦片坐标 self.rect = self.image.get_rect(topleft=self.tile) def update(self): # 若瓦片坐标会动态变化,这里同步更新rect位置 self.rect.topleft = self.tile
另外可以简化你的瓦片坐标生成逻辑,让代码更清晰:
tiles = [] for y in range(10): for x in range(10): tiles.append((x * tile_size, y * tile_size))
修改后,精灵就能正常渲染到目标位置了。
内容的提问来源于stack exchange,提问作者RaptoRR
相关产品推荐
相关产品推荐

