在 pygame 中使矩形透明

make a rect transparent in pygame

我正在尝试制作一种 Brick Breaker,但球周围矩形的透明度有问题。每次它碰到东西时,您都可以看到矩形。 有什么建议吗?它也迫使我使用白色背景 there is an image of the problem

import pygame
pygame.init()
bg_color = (255,255,255)
width, height = 600, 400
dx, dy = 2, 2
screen = pygame.display.set_mode((width, height))
screen.fill(bg_color)
ball = pygame.image.load("medicine-ball.png").convert()
ball = pygame.transform.scale(ball, (50, 50))
ball_rect = ball.get_rect()
ball_color = False
def rect(x1,y1,x2,y2):
    pygame.draw.rect(screen, (0,0,0), (x1,y1,x2,y2))
game_loop = True
while game_loop:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        game_loop = False
    ball_rect = ball_rect.move(dx,dy)
    if ball_rect.left < 0 or ball_rect.right > width:
        dx *= -1
    if ball_rect.top < 0 or ball_rect.bottom > height:
        dy *= -1

    mouse_pos = list(pygame.mouse.get_pos())
    rect(mouse_pos[0]-40,300-10,80,20)
    if ball_rect.bottom == 300 and ball_rect.x > mouse_pos[0]-89 and ball_rect.x < mouse_pos[0]+129:
        dy *= -1
    screen.blit(ball, ball_rect)
    pygame.time.wait(1)
    pygame.display.flip()
    screen.fill(bg_color)

另一件困扰我的事情是我无法改变球的速度,我很确定这是我 mac 的问题,因为它可以在我朋友的电脑上运行(它是关于pygame.time.wait())

如果你想让图片透明,你需要确保设置了图片的alpha通道。此外,您必须使用 convert_alpha() instead of convert():

if ball_color:
    ball = pygame.image.load("ball.png").convert_alpha()
else:
    ball = pygame.image.load("medicine-ball.png").convert_alpha()

另请参阅问题的答案:


make a rect transparent in pygame

不幸的是,没有绘制透明形状的好方法。见Draw a transparent rectangle in pygame and see pygame.draw模块问题的答案:

A color's alpha value will be written directly into the surface [...], but the draw function will not draw transparently.

因此你需要做一个解决方法:

  1. 创建一个 pygame.Surface 对象,每个像素的 alpha 格式足够大以覆盖形状。
  2. 在 _Surface 上绘制形状。
  3. Surface 与目标 Surface 混合。 blit() 默认混合 2 Surfaces

例如3个函数,可以绘制透明的矩形、圆形和多边形:

def draw_rect_alpha(surface, color, rect):
    shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
    pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
    surface.blit(shape_surf, rect)

在您的代码中使用函数而不是 pygame.draw.rectalpha 是 [0, 255]:

范围内的值
def rect(x1, y1, x2, y2, alpha = 255):
    #pygame.draw.rect(screen, (0,0,0), (x1,y1,x2,y2))
    draw_rect_alpha(screen, (0, 0, 0, alpha), (x1, y1, x2, y2))