python - Pygame - 精灵组运动不起作用
问题描述
我目前正在尝试对太空入侵者克隆进行编程。我创建了一个具有多个属性的“Invaders”-Class,并为我所有的敌方入侵者创建了一个精灵组。
class Invader(pygame.sprite.Sprite):
def __init__(self, settings, picture, x, y):
super().__init__()
self.settings = settings
self.x = x
self.y = y
self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()
self.image = pygame.transform.scale(self.image, (63,38))
self.rect = self.image.get_rect()
self.rect.center = [self.x, self.y]
def update(self):
direction_change = False
print(direction_change)
if self.rect.x > 800:
direction_change = True
else:
direction_change = False
if direction_change == False:
self.rect.x += 1
if direction_change == True:
self.rect.x -= 1
使用更新功能,我移动精灵组。但是当它移动到一个特定的点时,所有的精灵都会聚集在一起,它看起来像这样:
有没有办法像单个对象一样移动组?
解决方案
移动方向必须是类的属性Invader
。如果Sprite位于窗口的左侧或右侧,则更改方向:
class Invader(pygame.sprite.Sprite):
def __init__(self, settings, picture, x, y):
super().__init__()
self.settings = settings
self.x = x
self.y = y
self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()
self.image = pygame.transform.scale(self.image, (63,38))
self.rect = self.image.get_rect()
self.rect.center = [self.x, self.y]
self.direction = 1 # <---
def update(self):
if self.rect.right >= 800:
self.direction = -1
if self.rect.left <= 0:
self.direction = 1
self.rect.x += self.direction
推荐阅读
- python - 如何从数据框 B 中的列 (mother_age) 中减去数据框 A 中的列 (child_age)?
- c++ - 无法写入数据文件,尽管没有错误
- apache-kafka - apache kafka消费者的退避策略
- python - 如何在 pandas 数据框中对一列字符串进行排序,在其中强制按列排序的字母顺序?
- php - 如何在 CPanel Cron 作业中运行 PHPscript?
- c# - 如何在 C# 中动态地将类数组转换为 XML 文件?
- json - 在编译时不知道密钥的情况下解码 JSON 值
- vue.js - vue.js 的 ESLint 警告和错误 - vue/require-default-prop & vue/require-prop-type-constructor
- sql - MS Access - 迄今为止的字符串
- lit-element - mwc-icon 0.7.1 不渲染(使用 lit-element/pwa-starter-kit)?