如何解决为什么精灵不动?
我目前正在编写一个 pygame 游戏,你可以在屏幕上移动一艘宇宙飞船。目前,我已经到了我制造宇宙飞船并试图让它移动的部分。但是,当我尝试移动飞船时,飞船不动!
这是我当前的代码:
import pygame
pygame.init()
screen = pygame.display.set_mode((800,500))
screen.fill((255,255,255))
class Spaceship(pygame.sprite.Sprite):
def __init__(self,s,x,y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x,self.y = x,y
self.image = pygame.image.load("C:/eqodqfe/spaceship.png")
self.image = pygame.transform.scale(self.image,(175,175))
self.rect = self.image.get_rect()
self.rect.center = (self.x,self.y)
def update(self):
self.rect.center = (self.x,self.y)
spaceship = Spaceship(screen,400,400)
screen.blit(spaceship.image,spaceship.rect)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 5
elif key[pygame.K_d]:
spaceship.x += 5
elif key[pygame.K_w]:
spaceship.y += 5
elif key[pygame.K_s]:
spaceship.y -= 5
spaceship.update()
pygame.display.update()
我当前的代码有什么问题?
解决方法
您必须在应用程序循环中绘制Sprties:
clock = pygame.time.Clock()
running = True
while running:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 5
elif key[pygame.K_d]:
spaceship.x += 5
elif key[pygame.K_w]:
spaceship.y -= 5
elif key[pygame.K_s]:
spaceship.y += 5
# update the position of the object
spaceship.update()
# clear the display
screen.fill((255,255,255))
# draw the object
screen.blit(spaceship.image,spaceship.rect)
# update the display
pygame.display.update()
# limit frames per second
clock.tick(60)
典型的 PyGame 应用程序循环必须:
- 通过
pygame.event.pump()
或pygame.event.get()
处理事件。 - 根据输入事件和时间(分别为帧)更新游戏状态和对象位置
- 清除整个显示或绘制背景
- 绘制整个场景(
blit
所有对象) - 通过
pygame.display.update()
或pygame.display.flip()
更新显示 - 限制每秒帧数以限制 CPU 使用率
此外,我建议使用 pygame.sprite.Group
:
pygame.sprite.Group.draw()
和 pygame.sprite.Group.update()
是由 pygame.sprite.Group
提供的方法。
前者将 委托给包含的 pygame.sprite.Sprite
s 的 update
方法 - 您必须实现该方法。见pygame.sprite.Group.update()
:
对组中的所有 Sprite 调用 update()
方法 [...]
后者使用包含的 image
的 rect
和 pygame.sprite.Sprite
属性来绘制对象 - 您必须确保 pygame.sprite.Sprite
具有所需的属性。见pygame.sprite.Group.draw()
:
将包含的精灵绘制到 Surface 参数。这对源表面使用 Sprite.image
属性和 Sprite.rect
。 [...]
spaceship = Spaceship(screen,400,400)
all_sprites = pygame.sprite.Group()
all_sprites.add(spaceship)
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 5
elif key[pygame.K_d]:
spaceship.x += 5
elif key[pygame.K_w]:
spaceship.y += 5
elif key[pygame.K_s]:
spaceship.y -= 5
all_sprites.update()
screen.fill((255,255))
all_sprites.draw(screen)
pygame.display.update()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。