所以我从互联网上复制了一些代码( http://programarcadegames.com/python_examples/f.php?file=platform_moving.py )只是为了尝试 pygame...
我尝试将 self.image.fill(BLUE)
替换为 self.rect = pygame.image.load("TheArrow.png")
这是我的代码的一小段..
def __init__(self):
""" Constructor function """
# Call the parent's constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
width = 40
height = 60
self.image = pygame.Surface([width, height])
self.image.fill(BLUE)
self.rect = pygame.image.load("TheArrow.png")
# Set a referance to the image rect.
self.rect = self.image.get_rect()
# Set speed vector of player
self.change_x = 0
self.change_y = 0
# List of sprites we can bump against
self.level = None
这是原始代码...
def __init__(self):
""" Constructor function """
# Call the parent's constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
width = 40
height = 60
self.image = pygame.Surface([width, height])
self.image.fill(RED)
# Set a referance to the image rect.
self.rect = self.image.get_rect()
# Set speed vector of player
self.change_x = 0
self.change_y = 0
# List of sprites we can bump against
self.level = None
我希望显示图像 TheArrow.png
而不是矩形......
最佳答案
Rect
对象并不用于存储图像。 pygame.image.load() 返回带有图像的 Surface 。它可以直接使用,也可以在另一个 Surface
上使用 blitted。
def __init__(self):
""" Constructor function """
# Call the parent's constructor
super().__init__()
width = 40
height = 60
self.image = pygame.image.load("TheArrow.png") #use the image Surface directly
self.rect = self.image.get_rect()
#the rest as in the original code
或者:
def __init__(self):
""" Constructor function """
# Call the parent's constructor
super().__init__()
width = 40
height = 60
myimage = pygame.image.load("TheArrow.png")
self.image = pygame.Surface([width, height])
self.image.blit(myimage) #blit the image on an existing surface
self.rect = self.image.get_rect()
#the rest as in the original code
在前一种情况下,Surface
(其关联的矩形,您可以使用self.image.get_rect()
获取)的大小与加载的相同图像文件。
在后者中,您可以使用 [with, height]
设置大小。如果这些与图像尺寸不对应,图像将被剪切(如果更大)。
顺便说一句,将一个 Surface
传输到另一个 Surface
上就是在屏幕上显示 Surface 的方法。在 pygame 中,屏幕只是另一个 Surface
,有点特殊。
看看 intro tutorial了解更多信息。
关于python - 如何将 Sprite 从矩形更改为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55642923/