调整rect的图像

问题描述

我想移动一个 Rect 对象的图像,这可能吗?

示例: 1 - 用动画制作一个瀑布(使水图像滚动) 2 - 调整图像的位置而不是矩形

注意:这些只是示例,而不是我正在处理的代码

解决方法

您可以使用 pygame.Surface.scroll 将表面图像移动到位。例如,调用

water_surf.scroll(0,1)

然而,这不会让你满意。见pygame.Surface.scroll

将图像向右移动 dx 像素,向下移动 dy 像素。 dx 和 dy 分别对于向左和向上滚动可能为负。 未被覆盖的表面区域保留其原始像素值

您可能想编写一个函数来覆盖未被覆盖的区域,像素滚动出表面:

def scroll_y(surf,dy):
    scroll_surf = surf.copy()
    scroll_surf.scroll(0,dy)
    if dy > 0:
        scroll_surf.blit(surf,(0,dy-surf.get_height()))
    else:
        scroll_surf.blit(surf,surf.get_height()+dy))
    return scroll_surf

每帧一次,创建像瀑布一样的水流效果。

要在矩形区域中居中图像,您需要获取图像的边界矩形并将矩形的中心设置为通过该区域的中心。使用矩形blit图像:

area_rect = pygame.Rect(x,y,w,h)
image_rect = surf.get_rect()
image_rect.center = area_rect.center
screen.blit(surf,image_rect)

同一行:

screen.blit(surf,surf.get_rect(center = area_rect.center))

最小示例:

repl.it/@Rabbid76/PyGame-SCroll

import pygame

def scroll_y(surf,surf.get_height()+dy))
    return scroll_surf

pygame.init()
window = pygame.display.set_mode((400,400))
clock = pygame.time.Clock()

rain_surf = pygame.image.load('rain.png')
dy = 0

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          

    window_center = window.get_rect().center
    scroll_surf = scroll_y(rain_surf,dy)
    dy = (dy + 1) % rain_surf.get_height()

    window.fill(0)
    window.blit(scroll_surf,scroll_surf.get_rect(center = window_center))
    pygame.display.flip()

pygame.quit()
exit()