[英]How do you clear sprites in Pygame?
Pygame 为Group
类提供了clear
方法,该方法用于将精灵分组在一起。 当我在Group
对象上调用 clear 时,我可以成功清除该组中所有精灵的图像,但我的精灵的命中框仍然存在。 我想知道是否有另一种方法可以在不破坏精灵对象的情况下同时删除我的精灵图像和矩形命中框。
您应该使用组中的元素和要从组中删除的kill()
元素检查鼠标位置。 之后,您可以使用clean()
从屏幕中删除所有元素并再次使用 draw draw()
仅重绘仍在组中的元素
x, y = pygame.mouse.get_pos()
for item in my_group:
if item.rect.collidepoint(x, y):
print("Collision detected")
item.kill()
my_group.clear(screen, background)
my_group.draw(screen)
我在组中创建了两个元素,因此如果在clear()
之后删除draw()
,您会看到不同之处 - 它将从屏幕中删除所有元素
import pygame
# --- constants ---
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
SIZE = (700, 500)
# --- classes ---
class Block(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, color, width, height):
# Call the parent class (Sprite) 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.
self.image = pygame.image.load("Obrazy/images/square-1.png").convert()
# Fetch the rectangle object that has the dimensions of the image
# Update the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect()
# --- functions ---
# empty
# --- main ---
pygame.init()
# Set the height and width of the screen
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Testing Screen")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
my_block1 = Block(WHITE, 20, 20)
my_block2 = Block(WHITE, 20, 20)
my_block2.rect.x = 100
my_group = pygame.sprite.Group()
my_group.add(my_block1)
my_group.add(my_block2)
background = pygame.Surface(SIZE)
screen.fill(BLACK)
#screen.blit(background, (0,0))
my_group.draw(screen)
# -------- Main Program Loop -----------
while not done:
# Set the screen background
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
for item in my_group:
if item.rect.collidepoint(x, y):
print("Collision detected")
item.kill()
my_group.clear(screen, background)
my_group.draw(screen)
# Limit to 60 frames per second
clock.tick(60)
#my_group.clear(screen, background)
#my_group.draw(screen)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
顺便说一句:在 Python 3 中你可以使用
super().__init__()
代替
pygame.sprite.Sprite.__init__(self)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.