在我正在制作的游戏中,我有一个图像需要从(old_width,old_height)缩放到(new_width,new_height),这样它看起来就变得更大,并且我需要在游戏。
到目前为止,我已经尝试过使用 pygame.trasform.smoothscale,但由于某些原因,它所做的只是将图像沿着屏幕向右角移动。
我觉得很奇怪,因为我不明白发生了什么事。
这是处理图像的类:
class GrowingImage:
def __init__(self, image_path, x, y, width, height):
self.width = width
self.height = height
self.object_image = pygame.image.load(image_path)
self.image = pygame.transform.scale(self.object_image, (self.width, self.height))
self.x_pos = x
self.y_pos = y
def draw(self, background):
background.blit(self.image, (self.x_pos, self.y_pos))
def grow(self):
self.image = pygame.transform.smoothscale(self.object_image, (self.width, self.height))
self.width += 1
self.height += 1
这就是调用grow方法的地方。我删除了对于这个问题来说多余的所有其余内容,因此理论上图像此时应该无限增长:
image = GrowingImage('image.png', 400, 100, 405, 640)
while not is_game_over:
for event in pygame.event.get():
# Bunch of stuffs
# Redraw the screen
self.game_screen.fill(WHITE_COLOR)
image.grow()
image.draw()
# Display the screen
pygame.display.update()
# Tick the clock to update everything within the game.
clock.tick(self.TICK_RATE)
嗯,事实并非如此,我完全不知道为什么会发生这种情况。有人知道我在这里做错了什么吗?
图像并没有真正移动。它可能看起来像向右下角移动,因为它变得更大,即它的宽度和高度在增加,记住,从图像的左上角开始。这也是它被绘制的地方。因此,为了使其看起来像在生长,您可以将其绘制的位置偏移一半的宽度和高度,这基本上意味着偏移它,以便将其绘制在中心。更换
background.blit(self.image, (self.x_pos, self.y_pos))
与
background.blit(self.image, (self.x_pos - (self.width/2), self.y_pos - (self.height/2)))
工作示例
import pygame
class GrowingImage:
def __init__(self, image_path, x, y, width, height):
self.width = width
self.height = height
self.object_image = image_path
self.image = pygame.transform.scale(self.object_image, (self.width, self.height))
self.x_pos = x
self.y_pos = y
def draw(self, background):
background.blit(self.image, (self.x_pos - (self.width/2), self.y_pos - (self.height/2)))
def grow(self):
self.image = pygame.transform.smoothscale(self.object_image, (self.width, self.height))
self.width += 1
self.height += 1
pygame.init()
d = pygame.display.set_mode((600, 600))
image = pygame.Surface((1, 1))
growingImage = GrowingImage(image, 300, 300, 20, 20)
while True:
d.fill((255, 255, 255))
pygame.event.get()
growingImage.draw(d)
growingImage.grow()
pygame.display.update()
blit
的第二个参数可以是矩形。使用 pygame.Rect
对象,相对于图像中心缩放图像:
class GrowingImage:
def __init__(self, image_path, x, y, width, height):
self.object_image = pygame.image.load(image_path)
self.image = pygame.transform.scale(self.object_image, (self.width, self.height))
self.rect = self.image.get_rect(topleft = (x, y))
def draw(self, background):
background.blit(self.image, self.rect)
def grow(self):
w = self.rect.width + 1
h = self.rect.height + 1
self.image = pygame.transform.smoothscale(self.object_image, (w, h))
self.rect = self.image.get_rect(center = self.rect.center)
另请参阅变换比例和缩放表面