[英]Pygame sprite constantly redrawn to screen and not moving
我看不出下面的代码有什么问题。 我想要做的就是让青蛙在屏幕上移动,但它只是重新绘制了许多相隔一个像素的青蛙。 我如何移动青蛙而不是再次绘制它?
import pygame
from pygame.constants import *
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
class Frog(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.transform.scale(pygame.image.load('frog.png'), (64, 64))
self.rect = self.image.get_rect()
self.dx = 1
def update(self, *args):
self.rect.x += self.dx
running = True
frog = Frog()
entities = pygame.sprite.Group()
entities.add(frog)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
entities.update()
entities.draw(screen)
这就是您在 Pygame 中执行此操作的方式,您只需在每次迭代时重绘对象以产生它们正在移动的错觉,但您必须通过用纯色填充 window 来掩盖先前绘制的对象,例如
screen.fill((255, 255, 255))
这应该在你的游戏循环的开始,所以你有一个新的 canvas 用于在每次迭代中绘制你的对象。
while running:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == QUIT:
running = False
entities.update()
entities.draw(screen)
pygame.display.update()
您可能必须使用 pygame.display.update() function 来更新整个屏幕而不仅仅是您的实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.